import cityFinder from "../func/module/cityFinder";
import { missionDict } from "../dictionary/translation";
import getTaskHint from "../func/translate/getTaskHint";
import CommonUtils from "./utils/CommonUtils";
import SHOP_BEER_STATIC_ITEM_HTML from "../../static/html/buyBeer/shop_beer_static_item.html";
import ADD_BEER_HEAD_HTML from "../../static/html/buyBeer/add_beer_head.html";
import QUICK_CRIMES_HTML from "../../static/html/quick_crimes.html";
import RW_RIDER_HTML from "../../static/html/rw_rider.html";
import christmasTownHelper from "../func/module/christmasTownHelper";
import LotteryHelper from "../feature/LotteryHelper";
import TornStyleBlock from "./utils/TornStyleBlock";
import PTHelper from "./action/PTHelper";
import StackHelper from "../feature/StackHelper";
import BuyBeerHelper from "../feature/BuyBeerHelper";
import XZMZ from "./action/XZMZ";
import ProfileHelper from "./action/ProfileHelper";
import SearchHelper from "./action/SearchHelper";
import TornStyleSwitch from "./utils/TornStyleSwitch";
import SlotsHelper from "./action/SlotsHelper";
import globVars from "../globVars";
import { Injectable } from "../container/Injectable";
import ClassName from "../container/ClassName";
import LocalConfigWrapper from "./LocalConfigWrapper";
import { Container } from "../container/Container";
import Logger from "./Logger";

/**
 * 脚本区分页面的功能入口
 *
 * TODO 去除jq
 */
@Injectable()
@ClassName('UrlPattern')
export default class UrlRouter {
    constructor(
        private readonly localConfigWrapper: LocalConfigWrapper,
        private readonly buyBeerHelper: BuyBeerHelper,
        private readonly searchHelper: SearchHelper,
        private readonly lotteryHelper: LotteryHelper,
        private readonly slotsHelper: SlotsHelper,
        private readonly logger: Logger,
    ) {
    }

    public resolve(): void {
        let href = window.location.href;
        let modules = [];
        // 捡垃圾助手
        if (href.includes('city.php') && this.localConfigWrapper.config.cityFinder) {
            let _base = new TornStyleBlock('芜湖助手').insert2Dom();
            let reloadSwitch = new TornStyleSwitch('解决一直转圈(加载中)的问题');
            reloadSwitch.getInput().checked = this.localConfigWrapper.config.SolveGoogleScriptPendingIssue;
            _base.append(reloadSwitch.getBase()).insert2Dom();
            reloadSwitch.getInput().addEventListener('change', () => {
                if (reloadSwitch.getInput().checked) window.location.replace(window.location.href);
                this.localConfigWrapper.config.SolveGoogleScriptPendingIssue = reloadSwitch.getInput().checked;
                // WuhuConfig.set('SolveGoogleScriptPendingIssue', reloadSwitch.getInput().checked, true);
            });

            _base.append(document.createElement('br'));

            cityFinder(_base);
        }

        // pt一键购买
        if (href.includes('pmarket.php')) Container.factory(PTHelper);

        // 叠e助手
        if (href.includes('gym.php')) Container.factory(StackHelper);

        // 寻找木桩
        if (href.includes('item.php?temp=4')) {
            let hasInit: boolean = false;
            let handle = () => {
                if (!hasInit && window.location.hash === '#xunzhaomuzhuang') {
                    Container.factory(XZMZ).init();
                    hasInit = true;
                }
            }
            window.addEventListener('hashchange', handle);
            handle();
        }

        // 啤酒店
        if (href.includes('shops.php?step=bitsnbobs')) {
            let block = new TornStyleBlock('啤酒助手').insert2Dom();
            block.setContent(ADD_BEER_HEAD_HTML);
            const msg_node = block.querySelector('#wh-msg');
            // 加入啤酒
            block.querySelector('button').addEventListener('click', e => {
                let node = document.querySelector('ul.items-list');
                if (!node) {
                    msg_node.innerHTML = '❌ 商品未加载完';
                    this.logger.error('商品未加载完');
                    return;
                }
                if (node.querySelector('span[id="180-name"]')) {
                    msg_node.innerHTML = '❌ 页面已经有啤酒了';
                    this.logger.warn('商店页面已有啤酒');
                    return;
                }
                const clear_node = node.querySelector('li.clear');
                const beer = document.createElement('li');
                beer.classList.add('torn-divider', 'divider-vertical');
                beer.style.backgroundColor = '#c8c8c8';
                beer.innerHTML = SHOP_BEER_STATIC_ITEM_HTML;
                if (clear_node) clear_node.before(beer);
                else node.append(beer);
                (<HTMLInputElement>e.target).disabled = true;
                msg_node.innerHTML = '添加成功';
            });

            // 监听啤酒购买
            globVars.responseHandlers.push((...args: any[]) => this.buyBeerHelper.responseHandler.apply(this.buyBeerHelper, args));
        }

        // 快速crime TODO 重构、与翻译解藕
        if (href.contains(/crimes\.php/) && this.localConfigWrapper.config.quickCrime) {
            // iframe
            if (self !== top) {
                const isValidate = document.querySelector('h4#skip-to-content').innerText.toLowerCase().includes('validate');
                CommonUtils.elementReady('#header-root').then(e => e.style.display = 'none');
                CommonUtils.elementReady('#sidebarroot').then(e => e.style.display = 'none');
                CommonUtils.elementReady('#chatRoot').then(e => e.style.display = 'none');
                if (!isValidate) document.body.style.overflow = 'hidden';
                CommonUtils.elementReady('.content-wrapper').then(e => {
                    e.style.margin = '0px';
                    e.style.position = 'absolute';
                    e.style.top = '-35px';
                });
                CommonUtils.elementReady('#go-to-top-btn button').then(e => e.style.display = 'none');
            }
            const element = document.querySelector('.content-wrapper');
            const OB = new MutationObserver(() => {
                OB.disconnect();
                // titleTrans();
                // contentTitleLinksTrans();
                trans();
                OB.observe(element, {
                    characterData: true,
                    attributes: true,
                    subtree: true,
                    childList: true
                });
            });
            const trans = () => {
                const dom = QUICK_CRIMES_HTML;
                const hasInserted = element.querySelector('.wh-translate') !== null;
                // const is_captcha = element.querySelector('div#tab-menu.captcha') !== null;
                const $title = document.querySelector('div.content-title');
                const $info = document.querySelector('.info-msg-cont');
                // if (!hasInserted && !is_captcha) {
                if (!hasInserted) {
                    if ($title) $title.insertAdjacentHTML('beforebegin', dom);
                    else if ($info) $info.insertAdjacentHTML('beforebegin', dom);
                }
            };
            trans();
            OB.observe(element, {
                characterData: true,
                attributes: true,
                subtree: true,
                childList: true
            });
        }

        // 任务助手 TODO 重构、与翻译解藕
        if (href.contains(/loader\.php\?sid=missions/) && this.localConfigWrapper.config.missionHint) {
            const anchor = document.querySelector('.content-wrapper');
            const OB = new MutationObserver(() => {
                OB.disconnect();
                // titleTrans();
                // contentTitleLinksTrans();
                trans();
                OB.observe(anchor, {
                    characterData: true,
                    attributes: true,
                    subtree: true,
                    childList: true
                });
            });
            const taskList = {};
            const trans = () => {
                $('ul#giver-tabs a.ui-tabs-anchor').each((i, e) => {
                    let $e = $(e);
                    if ($e.children().hasClass('mission-complete-icon')) {
                        taskList[i] = e.innerText.trim();
                    } else {
                        taskList[i] = $e.clone().children().remove().end().text().trim();
                    }
                });
                // 助手注入
                $('div.max-height-fix.info').each((i, e) => {
                    let $e = $(e);
                    if ($e.find('.wh-translated').length !== 0) return;
                    $e.append(`<div class="wh-translated"><h6 style="color:green"><b>任务助手</b></h6><p>${ getTaskHint(taskList[i]) }</p></div>`);
                });
                // 任务目标
                $('ul.tasks-list span.title-wrap').contents().each((i, e) => {
                    if (e.nodeType === 3) {
                        if (missionDict[e.nodeValue.trim()]) {
                            e.nodeValue = missionDict[e.nodeValue.trim()];
                        }
                    }
                });
            };
            trans();
            OB.observe(anchor, {
                characterData: true,
                attributes: true,
                subtree: true,
                childList: true
            });
        }

        // 个人资料
        if (href.includes('profiles.php?XID=')) Container.factory(ProfileHelper);

        // 圣诞小镇
        if (href.contains(/christmas_town\.php/) && new Date().getMonth() > 9) christmasTownHelper();

        // rw雷达
        if (href.includes('profiles.php?XID=0')) {
            const utl = {
                set: function (k, v) {
                    const obj = JSON.parse(localStorage['wh_rw_raider']) || {};
                    obj[k] = v;
                    localStorage['wh_rw_raider'] = JSON.stringify(obj);
                },
                get: function (k) {
                    const obj = JSON.parse(localStorage['wh_rw_raider']) || {};
                    return obj[k];
                },
                setFactionID: function (id) {
                    this.set('faction', id);
                },
                setRWFactionID: function (id) {
                    this.set('rw_faction', id);
                },
                getFactionID: async function (apikey) {
                    const response = await window.fetch('https://api.torn.com/faction/?selections=basic&key=' + apikey);
                    const res_obj = await response.json();
                    const faction_id = res_obj['ID'];
                    if (faction_id) {
                        this.setFactionID(faction_id);
                        return faction_id;
                    } else return -1;
                },
                getRWFactionID: function (apikey) {
                },
            };
            const rw_raider = async function () {
                if (href.includes('#rader')) {
                    CommonUtils.addStyle('div.content-title,div.info-msg-cont{display:none;}');
                    const wh_node = document.createElement('div');
                    wh_node.id = 'wh-rd-cont';
                    wh_node.innerHTML = RW_RIDER_HTML;
                    // 原页面完全加载
                    await CommonUtils.elementReady('div.msg[role="alert"]');
                    const t_cont = document.querySelector('div.content-wrapper');
                    // t
                    t_cont.append(wh_node);
                }
            };
            addEventListener('hashchange', rw_raider);

            rw_raider().then();
        }

        // 彩票助手
        if (href.includes('loader.php?sid=lottery')) this.lotteryHelper.init();

        // 老虎机助手
        if (href.includes('loader.php?sid=slots')) this.slotsHelper.init();

        // 搜索助手
        if (href.includes('page.php?sid=UserList')) this.searchHelper.init();
    }
}
