import { selectAll, select } from 'd3-selection';
/*
Uses the Mediawiki API to display a list of recent images and a link to
the page where the image has been used/placed.

Makes use of the following API calls:

* https://www.mediawiki.org/wiki/API:Allimages
* https://www.mediawiki.org/wiki/API:Imageinfo
* https://www.mediawiki.org/wiki/API:Imageusage
*/
var PAGE_COUNT = 25; /* how many edits to show per load*/
var main = select("#content"),
    baseurl = "/mw/api.php?action=query&list=recentchanges&rclimit=25&rcnamespace=0&rctoponly=1&format=json&formatversion=2&rcshow=!minor|!bot|!redirect|!anon",
    url = baseurl;

async function get_json (url) {
    var resp = await fetch(url);
    return await resp.json();
}

function url_for_title (title) {
    return "/w/"+encodeURI(title.replace(/ /g, "_"));
}

async function load () {
    let count = 0;
    while (count < PAGE_COUNT) {
        // console.log("starting loop", "count", count, "url", url);
        let data = await get_json(url),
            recentchanges = data.query.recentchanges;
        console.log("recentchanges", recentchanges);
        let items = main.selectAll("div.edit")
            .data(recentchanges, d=>d.title)
            .enter()
            .append("div")
            .attr("class", "edit")
            .append("a")
            .attr("href", d=>url_for_title(d.title))
            .attr("target", "wikiframe")
            .text(d=>d.title);

        if (data.continue) {
            url = baseurl+"&rccontinue="+data.continue.rccontinue;
        } else {
            return;
        }
        count += recentchanges.length;
    }
}
document.addEventListener("DOMContentLoaded", load);
document.querySelector("a#more").addEventListener("click", function (e) {
    e.preventDefault();
    load();
});