Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
/* Checks if the current page has a wikidata image that isn't currently present */
/* Attribution for close icon: https://commons.wikimedia.org/wiki/File:Antu_application-exit.svg */
/* Possible other method:
    * Use API to get HTML of interlanguage links
    * Convert to Jquery HTML
    * Use selectors to get all images, excluding .icon .noview, etc
    * Add them all to a set
    * Go through enwiki images, removing the ones inside from the set
    * Find a way to display the resulting images

Alternative method: Use API props such as `images` or `pageimages`
    w/ a `langlinks` generator

TODO: Check out https://commons.wikimedia.org/wiki/Commons:JavaScript_styleguide#How_to_construct_URIs

License: CC0

Test page: https://en.wiki.x.io/wiki/Ronald_Barnes,_3rd_Baron_Gorell
*/

function setup() {
    // If we're not reading an article, do nothing
    if (!(mw.config.get("wgAction") === "view"
          && mw.config.get("wgIsArticle")
          && !location.search.split('oldid=')[1]
          && !mw.config.get("wgIsMainPage"))) {
        return;
    }

    // Make sure we have somewhere to put result
    if (!$("#contentSub").length) {
    	return;
    }

    if (wikidataId === null) {
        return;
    }

    // API docs: https://www.wikidata.org/w/api.php?action=help&modules=wbgetclaims
    $.ajax({
        url: "https://www.wikidata.org/w/api.php",
        data: {
            action: "wbgetclaims",
            entity: wikidataId,
            property: "P18",
            format: "json",
            origin: "*"
        },
        success: parseProperty
    });
}

function parseProperty(response) {
	var filename;
    if (typeof response.claims.P18 != "undefined") {
	    filename = response.claims.P18[0].mainsnak.datavalue.value;
    } else {
    	return;
    }

    filename = filename.replace(/ /g, "_");
	searchForImage(filename);
}

function searchForImage(filename) {
	var foundMatch;
	// See history for an inline implementation
	var filenameEscaped = mw.util.escapeRegExp(filename);
    var re = new RegExp(filenameEscaped);

    $("#bodyContent img").each(function() {
        var src = $(this).attr("src");
        // MediaWiki seems to encode anything not alphanumeric...
        src = decodeURI(src).replace(/%2C/g, ",").replace(/%3B/g, ";").replace(/%26/g, "&").replace(/%40/g, "@").replace(/%2B/g, "+");
        /* console.log("otherImages.js: filename: " + filename);
        console.log("otherImages.js: filename escaped: " + filenameEscaped);
        console.log("otherImages.js: src: " + src); */
        
        if (re.test(src)) {
            console.log("otherImages.js: Page already has wikidata image");
            $(this).attr('id', 'otherImages-pageImage');
            foundMatch = true;
            return false;
        }
    });

	if (!foundMatch) {
        getThumbUrl(filename);
	}
}

function getThumbUrl(filename) {
	// See: https://www.mediawiki.org/wiki/Help:Magic_words
	var thumbTemplate = "{{filepath:" + filename + "|100}}";

	// API docs: https://www.mediawiki.org/wiki/API:Expandtemplates
	var apiUrl = location.origin + "/w/api.php";
    $.ajax({
        url: apiUrl,
        data: {
            action: "expandtemplates",
            text: thumbTemplate,
            prop: "wikitext",
            format: "json",
        },
        success: function(response) {
        	var thumbUrl = response.expandtemplates.wikitext;
        	displayImage(filename, thumbUrl);
        }
    });
}

function displayImage(filename, thumbUrl) {
    var commonsUrl = "//commons.wikimedia.org/wiki/File:" + filename;
    var wikidataUrl = "https://www.wikidata.org/wiki/" + wikidataId + "#P18";

    var wikidataLogoMarkup = "<a href='" + wikidataUrl + "'><img src='" + wikidataLogoUrl + "'></a>";
    var thumbMarkup = "<a href=" + commonsUrl + "><img src='" + thumbUrl + "'></a>";
    var closeButtonMarkup = "<img id='closeButton' style='position: absolute; top: 0; right: 0; display: none;'"
                            + "src='" + closeButtonUrl + "'>";

    var containerMarkup = "<div id='otherImage' style='float: right; position: relative;'>"
                          + thumbMarkup + wikidataLogoMarkup + closeButtonMarkup
                          + "</div>";
    $("#contentSub").before(containerMarkup);
    addHandlers();
}

function addHandlers() {
	$("#otherImage").hover(function(){
		$("#otherImage #closeButton").show();
	}, function(){
		$("#otherImage #closeButton").hide();
	});
	
	$("#otherImage #closeButton").click(function() {
		$("#otherImage").remove();
	});
}

var wikidataId = mw.config.get( 'wgWikibaseItemId' );
var wikidataLogoUrl = "https://up.wiki.x.io/wikipedia/commons/thumb/f/ff/Wikidata-logo.svg/30px-Wikidata-logo.svg.png";
var closeButtonUrl = "https://up.wiki.x.io/wikipedia/commons/thumb/c/cc/Antu_application-exit.svg/25px-Antu_application-exit.svg.png";
$(setup);