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.
/*<nowiki>
	IdMatch
    Created by: Terasail
*/
var api = new mw.Api();
var wikidataIDMatch = false;
var matchCategories = ["Netflix title", "Disney+", "Metacritic", "IMDb title", "Rotten Tomatoes"];
var propertyNames = {//Name | Template name regex | URL prefixes regex
	P1874: ["Netflix title", "Netflix[ _]title", ""],
	X1P1712: ["Metacritic film", "Metacritic[ _](film|movie)", "(movie\\/)?"],
	X2P1712: ["Metacritic television", "Metacritic[ _](television|TV)", "(tv\\/)?"],
	X3P1712: ["Metacritic album", "Metacritic[ _](album|music)", "(music\\/)?"],
	P12054: ["Metacritic video game", "Metacritic[ _](video game|video games|vg|game)", ""],
	P7595: ["Disney+ movie", "Disney\\+[ _](movie|film)", ""],
	P7596: ["Disney+ series", "Disney\\+[ _]series", ""],
	P8298: ["HBOMax", "", ""],
	P345: ["IMDb title", "IMDb[_ -]?(title|film|movie)", "(tt)?"],
	P1258: ["Rotten Tomatoes", "Rotten[ _-]?Tomatoes", "((m|tv|franchise|celebrity|critics)\\/)?"]
};

//Check for matching category
for (let i = 0; i < matchCategories.length; i++) {
	if (mw.config.get("wgCategories").includes(matchCategories[i] + " ID same as Wikidata")) {
		wikidataIDMatch = true;
	}
}

//Add link to Tools-Actions
if (wikidataIDMatch) {
	$.when(mw.loader.using('mediawiki.util'), $.ready).then(function () {
		if (mw.config.get("wgCanonicalNamespace") != "Special") {
			let potletIDMatches = mw.util.addPortletLink(
				'p-cactions','',
				'Remove ID Matches',
				'ca-IDMatches',
				'Remove the ID values from templates which match Wikidata values',
				'',''
			);
			$(potletIDMatches).on('click', function (e) {
				e.preventDefault();
				findMatches();
			});
		}
	});
}

//Find which properties are in wikidata
function findMatches() {
    let apiTarget = "https://www.wikidata.org/w/api.php?action=wbgetclaims&format=json&origin=*&entity=" + mw.config.get("wgWikibaseItemId");
    api.get({
        action: "parse",
        page: mw.config.get("wgPageName"),
        prop: "wikitext"
    }).done(function(data) {
        let pageData = data.parse.wikitext["*"];
        fetch(apiTarget).then(function(response){return response.json();}).then(function(response) {
			let wikidataProperties = [];
			let propertyValues = Object.entries(propertyNames);
			let matchedProperties = [];
			for (let i=0; i < propertyValues.length; i++) {
				let propertyValue = propertyValues[i][0].replace(/X\d/, "");
				if (typeof(response.claims[propertyValue]) != 'undefined') {
					wikidataProperties.push(response.claims[propertyValue][0].mainsnak);
					matchedProperties.push(propertyValues[i][0]);
				}
			}
			runMatches(pageData, wikidataProperties, matchedProperties);
        });
    });
}

function runMatches(pageData, wikidataProperties, matchedProperties) {
	let pageTitle = mw.config.get("wgRelevantPageName").replaceAll(/[ _]/g, "[ _]");
	let wikidataItem = mw.config.get("wgWikibaseItemId");
	let tempPageData = pageData;
	let editSummary = "Removed id values that are stored at Wikidata from templates:";
	for (let i=0; i < wikidataProperties.length; i++) {
		let propertyValue = matchedProperties[i].replace(/X\d/, "");
		let propertyName = propertyNames[matchedProperties[i]];
		let wikidataValue = wikidataProperties[i].datavalue.value.replace(new RegExp(propertyName[2]), "");
		
		//Replace template with title parameter matching page title
		let templateRegex = new RegExp("{{ *" + propertyName[1] + " *\\| *(id *= *)?" + propertyName[2] + wikidataValue + "\\| *(title *= *)?" + pageTitle + " *(?=[|}])", "gi");
		tempPageData = tempPageData.replaceAll(templateRegex, "{{" + propertyName[0]);

		//Replace template with title parameter not matching page title
		templateRegex = new RegExp("{{ *" + propertyName[1] + " *\\| *(id *= *)?" + propertyName[2] + wikidataValue + "\\| *(title *= *)?", "gi");
		tempPageData = tempPageData.replaceAll(templateRegex, "{{" + propertyName[0] + "|title=");

		//Replace template without title parameter
		templateRegex = new RegExp("{{ *" + propertyName[1] + " *\\| *(id *= *)?" + propertyName[2] + wikidataValue + " *(?=[|}])", "gi");
		tempPageData = tempPageData.replaceAll(templateRegex, "{{" + propertyName[0]);

		//Update summary & PageData if changed
		if (pageData != tempPageData) {
			editSummary += " {{[[Template:" + propertyName[0] + "|" + propertyName[0] + "]]}} ([[d:" + wikidataItem + "#" + propertyValue + "|Claim]])";
			pageData = tempPageData;
		}
	}
	editSummary = editSummary.replaceAll(") {", "), {") + ". | [[User:Terasail/User Scripts#Private Scripts|Userscript]]";
	api.postWithEditToken({
        action: 'edit',
        title: mw.config.get("wgRelevantPageName"),
        text: pageData,
        summary: editSummary,
        minor: true
    }).done(function(result) {
        console.log(result);
        if (result.edit.result == "Success") {
			window.open(mw.util.getUrl(null, {type: 'revision', diff: 'cur', oldid: 'prev'}), "_self");
            //location.reload();
        }
    });
}
//</nowiki>[[Category:Wikipedia scripts]]