// ==UserScript==
// @name        Steam/GOG Games Links to Free Download Site
// @namespace   Kozinc
// @version     0.4.6
// @license      MIT
// @description  Simply adds a pirate link to all games on the GOG store
// @require      https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js
// @match        https://www.gog.com/game/*
// @match        https://www.gog.com/en/game/*
// @match        https://store.steampowered.com/app/*
// @grant		     GM_registerMenuCommand
// @grant              GM_getValue
// @grant              GM_setValue
// @grant              GM.getValue
// @grant              GM.setValue
// @grant		     GM_deleteValue
// @grant       GM_xmlhttpRequest
// @run-at      document-load
// @downloadURL none
// ==/UserScript==
/*
* usergui.js -- https://github.com/AugmentedWeb/UserGui/raw/Release-1.0/usergui.js
* v1.0.0
* https://github.com/AugmentedWeb/UserGui
* Apache 2.0 licensed
*/
class UserGui {
	constructor() {
		const grantArr = GM_info?.script?.grant;
		if(typeof grantArr == "object") {
			if(!grantArr.includes("GM_xmlhttpRequest")) {
				prompt(`${this.#projectName} needs GM_xmlhttpRequest!\n\nPlease add this to your userscript's header...`, "// @grant       GM_xmlhttpRequest");
			}
			if(!grantArr.includes("GM_getValue")) {
				prompt(`${this.#projectName} needs GM_getValue!\n\nPlease add this to your userscript's header...`, "// @grant       GM_getValue");
			}
			if(!grantArr.includes("GM_setValue")) {
				prompt(`${this.#projectName} needs GM_setValue!\n\nPlease add this to your userscript's header...`, "// @grant       GM_setValue");
			}
		}
	}
	#projectName = "UserGui";
	window = undefined;
	document = undefined;
	iFrame = undefined;
	settings = {
		"window" : {
			"title" : "No title set",
			"name" : "userscript-gui",
			"external" : false,
			"centered" : false,
			"size" : {
				"width" : 300,
				"height" : 500,
				"dynamicSize" : true
			}
		},
		"gui" : {
			"centeredItems" : false,
			"internal" : {
				"darkCloseButton" : false,
				"style" : `
					body {
						background-color: #ffffff;
						overflow: hidden;
						width: 100% !important;
					}
					form {
						padding: 10px;
					}
					#gui {
						height: fit-content;
					}
					.rendered-form {
						padding: 10px;
					}
					#header {
						padding: 10px;
						cursor: move;
						z-index: 10;
						background-color: #2196F3;
						color: #fff;
						height: fit-content;
					}
					.header-item-container {
						display: flex;
						justify-content: space-between;
						align-items: center;
					}
					.left-title {
						font-size: 14px;
						font-weight: bold;
						padding: 0;
						margin: 0;
					}
					#button-close-gui {
						vertical-align: middle;
					}
					div .form-group {
						margin-bottom: 15px;
					}
					#resizer {
						width: 10px;
						height: 10px;
						cursor: se-resize;
						position: absolute;
						bottom: 0;
						right: 0;
					}
					.formbuilder-button {
					    width: fit-content;
					}
				`
			},
			"external" : {
				"popup" : true,
				"style" : `
					.rendered-form {
						padding: 10px;
					}
					div .form-group {
						margin-bottom: 15px;
					}
				`
			}
		},
		"messages" : {
			"blockedPopups" : () => alert(`The GUI (graphical user interface) failed to open!\n\nPossible reason: The popups are blocked.\n\nPlease allow popups for this site. (${window.location.hostname})`)
		}
	};
	// This error page will be shown if the user has not added any pages
	#errorPage = (title, code) => `
		
		
			
				${title}
				${code}
				${this.#projectName} error message
			 
		 `;
	// The user can add multiple pages to their GUI. The pages are stored in this array.
	#guiPages = [
		{
			"name" : "default_no_content_set",
			"content" : this.#errorPage("Content missing", "Gui.setContent(html, tabName);")
		}
	];
	// The userscript manager's xmlHttpRequest is used to bypass CORS limitations (To load Bootstrap)
	async #bypassCors(externalFile) {
		const res = await new Promise(resolve => {
			GM_xmlhttpRequest({
			method: "GET",
			url: externalFile,
			onload: resolve
			});
		});
		return res.responseText;
	}
	// Returns one tab (as HTML) for the navigation tabs
	#createNavigationTab(page) {
		const name = page.name;
		if(name == undefined) {
			console.error(`[${this.#projectName}] Gui.addPage(html, name) <- name missing!`);
			return undefined;
		} else {
			const modifiedName = name.toLowerCase().replaceAll(' ', '').replace(/[^a-zA-Z0-9]/g, '') + Math.floor(Math.random() * 1000000000);
			const content = page.content;
			const indexOnArray = this.#guiPages.map(x => x.name).indexOf(name);
			const firstItem = indexOnArray == 0 ? true : false;
			return {
				"listItem" : `
					Search for ' + appName +': 
 ');
            // Create and insert the style element for custom CSS rules
            var style = document.createElement('style');
            style.innerHTML = `
                .pirate_row {
                    display: flex;
                }
                .pirate_row, .pirate_row .column {
                    white-space: normal !important;
                }
                .pirate_row .column {
                    color: #556772;
                }
                .pirate_row .subtitle {
                    text-transform: uppercase;
                    font-size: 10px;
                    padding-right: 10px;
                    min-width: 120px;
                }
                .pirate_row .summary {
                    overflow: hidden;
                    text-overflow: ellipsis;
                    color: #556772;
                }
                .pirate_row:hover {
                    background-color: #333; /* Dark grey background on hover */
                }
            `;
            document.head.appendChild(style);
        }
        ////////////
        if (steamDisplaySidebar) {
            savedButtonSet.forEach((el) => {
                $(".block.responsive_apppage_details_left:first").append(furnishSteamSidebar(el.url+appName + el.urlSpecial, el.title, appName))
                // $(".glance_ctn_responsive_left:first").append(furnishSteamSidebar(el.url+appName + el.urlSpecial, el.title, appName))
            })
        }
        if (steamDisplayCart) {
            savedButtonSet.forEach((el) => {
                $(".game_purchase_action_bg:first").append(furnishSteam(el.url+appName + el.urlSpecial, el.title))
            })
        }
        break;
    case "IGG":
        appName = $(".uk-article-title")[0].innerHTML.replace(" Free Download","");
        appName = appName.trim().replace(/[^a-zA-Z0-9 ]/g, '');
        savedButtonSet.forEach((el) => {
            $(".uk-article-meta")[0].append("  --  ")
            $(".uk-article-meta")[0].append(furnishIGG(el.url+appName, el.title))
        })
        break;
}
function furnishGOG(href, innerHTML) {
    let element = document.createElement("a");
    element.target= "_blank";
    element.style = "margin: 5px 0 5px 0 !important; padding: 5px 10px 5px 10px;";
    element.classList.add("button");
    //element.classList.add("button--small");
    element.classList.add("button--big");
    element.classList.add("cart-button");
    element.classList.add("ng-scope");
    element.href = href;
    element.innerHTML= innerHTML;
    return element;
}
function furnishSteam(href, innerHTML) {
    let element = document.createElement("a");
    element.target= "_blank";
    element.style = "margin-left: 10px; padding-right: 10px;";
    element.href = href;
    element.innerHTML= innerHTML;
    return element;
}
function furnishSteamSidebar(searchUrl, appName, gameName) {
    // Create the main container div
    var devRowDiv = document.createElement('div');
    devRowDiv.className = 'dev_row pirate_row';
    // Create the subtitle div
    var subtitleDiv = document.createElement('div');
    subtitleDiv.className = 'subtitle column';
    subtitleDiv.innerHTML = appName + ':';
    // Create the summary div
    var summaryDiv = document.createElement('div');
    summaryDiv.className = 'summary column';
    // Create the anchor element
    var anchor = document.createElement('a');
    anchor.href = searchUrl;
    anchor.target = '_blank';
    // anchor.innerHTML = 'Search ' + appName + ' for ' + gameName;
    anchor.innerHTML = appName;
    // Append the anchor to the summary div
    summaryDiv.appendChild(anchor);
    // Append the subtitle and summary divs to the main container div
    devRowDiv.appendChild(subtitleDiv);
    devRowDiv.appendChild(summaryDiv);
    // Return the created element
    return devRowDiv;
}
function furnishIGG(href, innerHTML) {
    let element = document.createElement("a");
    element.target= "_blank";
    element.href = href;
    element.innerHTML= innerHTML;
    return element;
}
try{ GM_registerMenuCommand = GM_registerMenuCommand || this.GM_registerMenuCommand; }catch(e){ GM_registerMenuCommand = false; }
if(p !== "true"){
  if(GM_registerMenuCommand){
    GM_registerMenuCommand('Show unsafe websites', function(){
      if(confirm('Are you sure you want to show possibly unsafe websites?\n'+
        '(It can be hidden later with this menu)')){
        GM_setValue("enableUnsafeButtonSet", "true");
        GM_deleteValue("enabledButtonSet");
        location.reload();
      }
    });
  }
} else if (GM_registerMenuCommand) {
  GM_registerMenuCommand('Hide unsafe websites', function(){
    if(confirm('Are you sure you want to hide possibly unsafe websites?\n'+
        '(It can be shown later with this menu)')){
      GM_deleteValue("enableUnsafeButtonSet");
      GM_deleteValue("enabledButtonSet");
      location.reload();
    }
  });
}
if (GM_registerMenuCommand) {
  GM_registerMenuCommand('Open Settings GUI', function(){
    openSettingsGui();
  });
}
if (GM_registerMenuCommand) {
  GM_registerMenuCommand('Reset settings', function(){
      GM_deleteValue("enableUnsafeButtonSet");
      GM_deleteValue("enabledButtonSet");
      GM_deleteValue("steamDisplaySidebar");
      GM_deleteValue("steamDisplayCart");
      GM_deleteValue("gogDisplaySidebar");
      GM_deleteValue("gogDisplayCart");
      location.reload();
  });
}