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 NUM_FILES = 10; /* how many files to show */
var main = select("#content"),
    baseurl = "/mw/api.php?action=query&list=allimages&ailimit=1&format=json&formatversion=2&aisort=timestamp&aidir=older&aiprop=timestamp|user|url|mime|size",
    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 < NUM_FILES) {
        // console.log("starting loop", "count", count, "url", url);
        let data = await get_json(url),
            allimages = data.query.allimages,
            useimages = [];

        // console.log("got data", data.query.allimages.length);
        for (var i=0, l=allimages.length; i<l; i++) {
            let image = allimages[i];
            // console.log("image", image.name);
            let iu_data = await get_json(`/mw/api.php?action=query&list=imageusage&iutitle=${image.title}&iunamespace=0&format=json&formatversion=2`);
            image.imageusage = iu_data.query.imageusage;
            if (image.imageusage.length == 0) { 
                continue;
            }
            let ii_data = await get_json(`/mw/api.php?action=query&prop=imageinfo&titles=${image.title}&iiprop=url|size&dimensions|mime&iiurlwidth=320&format=json&formatversion=2`);
            image.imageinfo = ii_data.query.pages[0].imageinfo[0];
            if (!image.imageinfo.thumburl) {
                continue;
            }
            useimages.push(image);
        }
        let items = main.selectAll("div.file")
            .data(useimages, d=>d.title)
            .enter()
            .append("div")
            .attr("class", "file")
            .append("a")
            .attr("href", d=>url_for_title(d.imageusage[d.imageusage.length-1].title))
            .attr("target", "wikiframe")
            .append("img")
            .attr('src', d=>d.imageinfo.thumburl);

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