import UserScriptEngine from "../../enum/UserScriptEngine";
import CommonUtils from "../../class/utils/CommonUtils";
import Alert from "../../class/utils/Alert";
import { Container } from "../../container/Container";
import Logger from "../../class/Logger";

// gs loader
export default function loadGS(use) {
    let logger = Container.factory(Logger);
    if (use === UserScriptEngine.PDA) {
        let ifr: HTMLIFrameElement = document.querySelector('#wh-gs-loader-ifr');
        if (ifr) {
            new Alert('飞贼小助手已经加载了');
            return;
        }
        const container = document.createElement('div');
        container.id = 'wh-gs-loader';
        ifr = document.createElement('iframe');
        ifr.id = 'wh-gs-loader-ifr';
        ifr.src = 'https://www.torn.com/crimes.php';
        container.append(ifr);
        document.body.append(container);
        CommonUtils.addStyle(`
#wh-gs-loader {
position:fixed;
top:0;
left:0;
z-index:100001;
}
`);
        let notify = new Alert('加载中');
        ifr.onload = () => {
            notify.close();
            const _window = ifr.contentWindow;
            const _docu = _window.document;
            _docu.head.innerHTML = '';
            _docu.body.innerHTML = '';
            notify = new Alert('加载依赖');
            CommonUtils.COFetch('https://cdn.staticfile.org/vue/2.2.2/vue.min.js')
                .then(vuejs => {
                    notify.close();
                    _window.eval(vuejs);
                    _window.GM_getValue = (k, v = undefined) => {
                        const objV = JSON.parse(_window.localStorage.getItem('wh-gs-storage') || '{}')[k];
                        return objV || v;
                    };
                    _window.GM_setValue = (k, v) => {
                        const obj = JSON.parse(_window.localStorage.getItem('wh-gs-storage') || '{}');
                        obj[k] = v;
                        _window.localStorage.setItem('wh-gs-storage', JSON.stringify(obj));
                    };
                    _window.GM_xmlhttpRequest = function (opt) {
                        // 暂不适配pda post
                        if (opt.method.toLowerCase() === 'post') return;
                        CommonUtils.COFetch(opt.url).then(res => {
                            const obj = {
                                responseText: res
                            };
                            opt.onload(obj);
                        });
                    };
                    notify = new Alert('加载飞贼小助手');
                    CommonUtils.COFetch(`https://gitee.com/ameto_kasao/tornjs/raw/master/GoldenSnitch.js?${ performance.now() }`)
                        .then(res => {
                            _window.eval(res.replace('http://222.160.142.50:8154/mugger', `https://api.ljs-lyt.com/mugger`));
                            _window.GM_setValue("gsp_x", 10);
                            _window.GM_setValue("gsp_y", 10);
                            notify.close();
                            notify = new Alert('飞贼小助手已加载', { timeout: 1 });
                            const gsp: HTMLElement = _docu.querySelector('#gsp');
                            const thisRun = () => {
                                ifr.style.height = `${ gsp.offsetHeight + 10 }px`;
                                ifr.style.width = `${ gsp.offsetWidth + 20 }px`;
                                gsp.style.top = '10px';
                                gsp.style.left = '10px';
                            };
                            new MutationObserver(thisRun).observe(gsp, { childList: true, subtree: true });
                            thisRun();
                            if (logger.debug()) _window.GM_setValue("gsp_showContent", true)
                        });
                });
        };
        return;
    }
    if (use === UserScriptEngine.GM) {
        if (typeof window.Vue !== 'function') {
            let notify = new Alert('正在加载依赖');
            CommonUtils.COFetch('https://cdn.staticfile.org/vue/2.2.2/vue.min.js')
                .then(VueJS => {
                    window.eval(VueJS);
                    notify.close();
                    notify = new Alert('已载入依赖');
                    window.GM_getValue = (k, v = undefined) => {
                        const objV = JSON.parse(window.localStorage.getItem('wh-gs-storage') || '{}')[k];
                        return objV || v;
                    };
                    window.GM_setValue = (k, v) => {
                        const obj = JSON.parse(window.localStorage.getItem('wh-gs-storage') || '{}');
                        obj[k] = v;
                        window.localStorage.setItem('wh-gs-storage', JSON.stringify(obj));
                    };
                    // TODO
                    // window.GM_xmlhttpRequest = GM_xmlhttpRequest;
                    CommonUtils.COFetch(`https://gitee.com/ameto_kasao/tornjs/raw/master/GoldenSnitch.js?${ performance.now() }`)
                        .then(GSJS => {
                            window.eval(GSJS);
                            if (logger.debug()) window.GM_setValue("gsp_showContent", true);
                            notify.close();
                            notify = new Alert('已载入飞贼助手');
                        })
                        .catch(err => new Alert(`PDA API错误。${ JSON.stringify(err) }`));
                })
                .catch(err => new Alert(JSON.stringify(err)));
        } else {
            new Alert('飞贼助手已经加载了');
        }
        return;
    }
    new Alert('暂不支持');
}