// ==UserScript==
// @name           TSOlastBreath
// @namespace      TSOlastBreath
// @description    Allow run TSO in old client
// @author         Sin aka SirriS
// @grant          none
// @version        2.0 (edited)
// @include        https://www.thesettlersonline.com.br/*
// @include        https://www.thesettlersonline.com/*
// @include        https://www.thesettlersonline.net/*
// @include        https://www.thesettlersonline.fr/*
// @include        https://www.thesettlersonline.cz/*
// @include        https://www.diesiedleronline.de/*
// @include        https://www.thesettlersonline.gr/*
// @include        https://www.thesettlersonline.it/*
// @include        https://www.juego-thesettlersonline.com/*
// @include        https://www.thesettlersonline.nl/*
// @include        https://www.thesettlersonline.pl/*
// @include        https://www.thesettlersonline.ro/*
// @include        https://www.thesettlersonline.ru/*
// @include        https://www.thesettlersonline.es/*
// ==/UserScript==

(function() {
var li1 = document.createElement ('li');
    li1.className = "active main ";
    li1.innerHTML = '<span></span><a id="clbutton" href="https://settlersonlinewiki.eu/" alt="Go to the wiki site" title="Go to the wiki site" target="_blank"><b>SettlersOnlineWiki</b></a>';
    document.querySelector("#menu ul").appendChild(li1);

    var li = document.createElement ('li');
    li.className = "promotion first ";
    li.innerHTML = '<span></span><a id="clplay" href="#" alt="Play with the TSO Client" title="Play with the TSO Client"><img src="https://forum.thesettlersonline.pl/images/settlers/buttons/lastpost-right.png" width="16" height="16" align="center" valign="center"></img><b>&nbsp Play by the Client &nbsp<img src="https://en.tsomaps.com/images/adventures/type/007.png" width="16" height="16" align="center" valign="center"></img></font></b></a>';
    if(document.querySelector(".jsInstance-logout") == null)
        return;
    document.querySelector("#menu ul").appendChild(li);

var url = new URL(window.location.href);
    document.getElementById("clplay").onmouseover = function() {document.getElementById("clplay").style.color = "#ffffff"};
    document.getElementById("clplay").onmouseout = function() {document.getElementById("clplay").style.color = "#000000"};
    document.getElementById("clplay").addEventListener("click", async () => {
    var playNowUrl = (/playNowforwardUrl = "(.+)";/g.exec(document.body.innerHTML))[1];
    if (!playNowUrl) {
        alert("something went wrong playNowforwardUrl");
        return;
    }
    var request = await fetch(url.origin + playNowUrl, {
            method: 'GET',
            credentials: 'include',
            redirect: 'manual'
        });
    var body = await request.text();
    var tso = (/return "(.*)"/g.exec(body))[1];
    window.location.href = "tso://"+tso+"&baseUri="+encodeURIComponent(url.origin);
    return;
    window.location.href = "tso://"+tso+"&baseUri="+url.origin;
    return;
  });
})();