// ==UserScript==
// @name         florr.io | Notify
// @version      1.0.2
// @description  Yes
// @author       sk
// @match        https://florr.io/*
// @grant        unsafeWindow
// ==/UserScript==
if(undefined !== window.Notification) {
    if (Notification.permission === "default") {
        Notification.requestPermission();
    }
}
Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
    var nnnn = new Date().Format("yyyy-MM-dd HH:mm:ss");
    var script_id = 6;
    var news_id = 0;
    var mapID;
var jjs = {};
// Simple GET request using fetch
fetch('https://api.ztrztr.top/api/fn_u', {method : "GET"})
  .then(response => response.json())
  .then(data => {
    console.log(data)
    console.log(data.update);
    console.log("114514")
    if (data.update > script_id) alert("有更新,请在 https://blog.ztrztr.top/310-2 下载最新版!" + data.msg)
    console.log(data);
});

var totalServers = 16,
    version = script_id

let url;
const nativeWebSocket = unsafeWindow.WebSocket;
unsafeWindow.WebSocket = function(...args){
    const socket = new nativeWebSocket(...args);
    url = socket.url
    return socket;
};

let cp6 = unsafeWindow.cp6

var servers = [],
    mapName,
    regionName,
    codeA = [],
    code;
for (let i = 0; i <= totalServers; i++) {
    fetch("https://api.n.m28.io/endpoint/florrio-map-" + i + "-green/findEach/").then((response) => response.json()).then((data) => {
        servers[i] = `${data.servers["vultr-miami"].id} ${data.servers["vultr-frankfurt"].id} ${data.servers["vultr-tokyo"].id}`
    })
};
try {
    var getPlayerName = [];
    function getMessage(text) {
        function discord(content, mobName, mobLevel, player) {
            var role = "",
                color = 0,
                status = "";

            if (regionName == "NA") code = servers[mapID].split(" ")[0];
            else if (regionName == "EU") code = servers[mapID].split(" ")[1];
            else if (regionName == "AS") code = servers[mapID].split(" ")[2];
            if (player == null) {
                if (mobLevel == "Ultra") {
                    role = "<@&1083713842615423016>";
                    color = 0xFF2B75
                } else if (mobLevel == "Super") {
                    role = "<@&1083723152619749428>";
                    color = 0x2BFFA3
                }
                status = `has spawned in`
                let n = new Notification('Ultra Mobs SPAWNED!', {
                    body: 'Ultra Mobs SPAWNED!',
                    icon: 'https://static.florr.io/c1c88b6cd810132c47da913d252af11e65142d12/favicon-32x32.png'
                })
            } else if (player == "") {
                status = `was defeated in`
            } else {
                status = `was defeated by ${player} in`;
            }
            var fetchurl = `https://ul.ztrztr.top/api/u?mobName=${mobName}&reg=${regionName}`
            console.log(fetchurl);
                fetch(fetchurl, {method : "GET", mode : "no-cors"})
            const imageDataUrl = canvas.toDataURL();
            const json = {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    content: `${regionName}: ${text} ${role}`,
                    embeds: [{
                        title: `${mapName}: The ${mobLevel} ${mobName} ${status} ${regionName} @everyone !`,
                        description: `${content}\n\`\`\`js\ncp6.forceServerID('${code}')\`\`\``,
                        color: color,
                        set_image: imageDataUrl,
                        footer: {
                            text: "Reported by " + getPlayerName.at(-2) + " - v" + version
                        }
                    }],
                }),
            };
            fetch('https://discord.com/api/webhooks/1092750373057474630/Cax_xo6q3Kn7hhnCp5YEyJt2ZVmW6NazJR24DXG4IgsOs04Nb215ZZTwbzoOYFyjjU0p', json);
            if (player != null) {
                json.body = JSON.stringify({content: `\`\`\`${mobName}, ${regionName}, ${Math.floor(Date.now() / 1000)}\`\`\``});
                fetch('https://discord.com/api/webhooks/1093489378044686416/xNEVlkw8ujfF3zshYATd7BRKve290ru5v7zE16xt0rXJgbWKUmdy9JURUYsqSkJinD5x', json);
            }
        }

        function AFK() {
                let n = new Notification('afk CHECK!', {
                    body: 'AFK Check!',
                    icon: 'https://static.florr.io/c1c88b6cd810132c47da913d252af11e65142d12/favicon-32x32.png'
                })
        }
        switch (true) {
            case (/The \w\w\w\w\w?\w?\w?\w?\w? .+ was defeated!/.test(text)): {
                const mobLevel = text.match(/(?<=The\s)\w\w\w\w\w?\w?\w?\w?\w?(?=\s)/);
                const mobName = text.match(/(?<=The\s\w\w\w\w\w?\w?\w?\w?\w?\s).+(?=\swas)/);
                discord(text, mobName[0], mobLevel[0], "");
                break
            }
            case (/The \w\w\w\w\w?\w?\w?\w?\w? .+ was defeated by .+!/.test(text)): {
                const mobLevel = text.match(/(?<=The\s)\w\w\w\w\w?\w?\w?\w?\w?(?=\s)/);
                const mobName = text.match(/(?<=The\s\w\w\w\w\w?\w?\w?\w?\w?\s).+(?=\swas)/);
                const playerName = text.match(/(?<=was defeated by ).+(?=!)/);
                discord(text, mobName[0], mobLevel[0], playerName[0]);
                break
            }
            case (/An? \w\w\w\w\w .+ has spawned!/.test(text)): {
                const mobLevel = text.match(/(?<=An?\s)\w\w\w\w\w(?=\s)/);
                const mobName = text.match(/(?<=An?\s\w\w\w\w\w\s).+(?= has spawned!)/);
                discord(text, mobName[0], mobLevel[0]);
                break
            }
            case (/An? \w\w\w\w\w .+ has spawned somewhere!/.test(text)): {
                const mobLevel = text.match(/(?<=An?\s)\w\w\w\w\w(?=\s)/);
                const mobName = text.match(/(?<=An?\s\w\w\w\w\w\s).+(?= has spawned somewhere!)/);
                discord(text, mobName[0], mobLevel[0]);
                break
            }
            case(text == 'AFK Check') :{
                AFK();
                break;
            }

        }
        if (!getPlayerName.includes('Ready')) {
            getPlayerName.push(text)
        }
        return text;
    }

    function getCompatibleCanvas() {
        if (typeof(OffscreenCanvasRenderingContext2D) == 'undefined') {
            return [CanvasRenderingContext2D]
        }
        return [OffscreenCanvasRenderingContext2D, CanvasRenderingContext2D];
    }
    for (const {
        prototype
    }
         of getCompatibleCanvas()) {
        if (prototype.rewriteArc == undefined) {
            prototype.rewriteMeasureText = prototype.measureText;
        } else {
            break
        }
    }
    for (const {
        prototype
    }
         of getCompatibleCanvas()) {
        prototype.measureText = function(text) {
            return this.rewriteMeasureText(getMessage(text));
        }
    }
} catch (e) {
    console.error(e)
}
function getServerId() {
    var wssUrl = url.slice(6, 10)
    servers.forEach(function callback(x, index) {
        if (x.includes(wssUrl)) {
            mapName = "MAP" + index
            mapID = index;
            codeA = x.split(" ")
            if (wssUrl == codeA[0]) regionName = "NA"
            else if (wssUrl == codeA[1]) regionName = "EU"
            else if (wssUrl == codeA[2]) regionName = "AS"
        }
    });
}

var urlA = []
setInterval(function() {
    urlA.unshift(url)
    if (urlA.length > 2) urlA.splice(2)
    if (urlA.at(-1) != urlA[0]) {
        getServerId()
    }
}, 1000)