import CommonUtils from "../utils/CommonUtils";
import QUICK_FLY_CSS from "../../../static/css/quick_fly.module.css";
import QUICK_FLY_HTML from "../../../static/html/quick_fly.html";
import Alert from "../utils/Alert";
import TravelItem from "../../feature/TravelItem";
import ClassName from "../../container/ClassName";
import { Injectable } from "../../container/Injectable";
import Logger from "../Logger";
import MsgWrapper from "../utils/MsgWrapper";
import { InjectionKey } from "vue";
import NetHighLvlWrapper from "../utils/NetHighLvlWrapper";

@ClassName('QuickFlyBtnHandler')
@Injectable()
export default class QuickFlyBtnHandler {
    className = 'QuickFlyBtnHandler';

    constructor(
        private readonly logger: Logger,
        private readonly travelItem: TravelItem,
        private readonly commonUtils: CommonUtils,
        // private readonly infoUtils: InfoUtils,
        private readonly msgWrapper: MsgWrapper,
        private readonly netHighLvlWrapper: NetHighLvlWrapper,
    ) {
    }

    public static doQuickFly(): void {
        // [id: dest, _type: (1...4), ts: timestamp]
        const [_id, _type, ts] = window.sessionStorage['wh-quick-fly'].trim().split(' ');
        if (new Date().getTime() - ts > 20000) {
            new Alert('超时，一键起飞计划已取消');
            return;
        }
        const keyNode = document.querySelector('div[data-id][data-key]');
        if (!keyNode) {
            new Alert('出错了，无法起飞，已取消');
            return;
        }
        const _key = keyNode.getAttribute('data-key');
        window.getAction({
            type: 'post',
            data: {
                step: 'travel',
                id: QuickFlyBtnHandler.getDestId(_id),
                key: _key,
                type: ['standard', 'airstrip', 'private', 'business'][_type]
            },
            success: function (str) {
                new Alert(str)
                if (str.includes('err')) {
                    new Alert('起飞出错了');
                    return;
                }
                window.location.href = 'https://www.torn.com/index.php'
            },
            before: function () {
            }
        });
        delete sessionStorage['wh-quick-fly'];
    }

    // 起飞目的地id
    private static getDestId(dest: number): number {
        // 墨、开、加、夏、英、阿、瑞s、立本、祖、迪、南
        return [2, 12, 9, 3, 10, 7, 8, 5, 6, 11, 4][dest];
    }

    public handle(): void {
        if (window.hasWHQuickFlyOpt) return;
        window.hasWHQuickFlyOpt = true;
        // TODO
        this.commonUtils.styleInject(QUICK_FLY_CSS);
        const node = document.createElement('div');
        node.id = 'wh-quick-fly-opt';
        node.innerHTML = QUICK_FLY_HTML;
        const [dest_node, type_node] = node.querySelectorAll('select') as any as HTMLSelectElement[];
        node.querySelector('button').addEventListener('click', () => {
            sessionStorage['wh-quick-fly'] = `${ dest_node.selectedIndex } ${ type_node.selectedIndex } ${ new Date().getTime() }`;
            if (!window.location.href.contains('travelagency.php')) {
                new Alert('正在转跳');
                location.href = 'https://www.torn.com/travelagency.php';
            } else {
                QuickFlyBtnHandler.doQuickFly();
            }
        });
        node.querySelector('a').addEventListener('click', (e) => {
            e.preventDefault();
            this.travelItem.clickHandler().then();
        });
        node.querySelector('input').addEventListener('click', (e) => {
            node.classList.toggle('wh-quick-fly-opt-hide');
            const el = e.target as HTMLInputElement;
            el.value = el.value === ' - ' ? ' + ' : ' - ';
        });
        const info_node = node.querySelector('info');
        const time_predict = document.createElement('p');
        const yaoCD = document.createElement('p');
        info_node.append(time_predict);
        info_node.append(yaoCD);
        const predict = [
            ['~54分', '~36分', '~26分', '~16分',],
            ['~1时10分', '~50分', '~36分', '~22分',],
            ['~1时22分', '~58分', '~40分', '~24分',],
            ['~4时28分', '~3时8分', '~2时14分', '~1时20分',],
            ['~5时18分', '~3时42分', '~2时40分', '~1时36分',],
            ['~5时34分', '~3时54分', '~2时46分', '~1时40分',],
            ['~5时50分', '~4时6分', '~2时56分', '~1时46分',],
            ['~7时30分', '~5时16分', '~3时46分', '~2时16分',],
            ['~8时4分', '~5时38分', '~4时2分', '~2时24分',],
            ['~9时2分', '~6时20分', '~4时30分', '~2时42分',],
            ['~9时54分', '~6时56分', '~4时58分', '~2时58分',],
        ];
        const showTime = function () {
            time_predict.innerHTML = `往返时间：${ predict[dest_node.selectedIndex][type_node.selectedIndex] }`;
        }
        dest_node.addEventListener('change', showTime);
        type_node.addEventListener('change', showTime);
        document.body.append(node);
        showTime();
        yaoCD.innerHTML = `药CD剩余：${ CommonUtils.getYaoCD() }`;
    }

    public async directFly(destIndex: number, typeIndex: number) {
        // 获取key
        let key;
        try {
            const resp = await (await fetch('/travelagency.php')).text();
            key = resp.match(/data-key="([0-9]+)"/)[1];
        } catch (e) {
            this.msgWrapper.create('起飞参数获取失败', {}, 'error');
            this.logger.error(e.stack);
            throw new Error('起飞参数获取失败');
        }
        let msg;
        try {
            msg = this.netHighLvlWrapper.doTravelFly(QuickFlyBtnHandler.getDestId(destIndex), key, ['standard', 'airstrip', 'private', 'business'][typeIndex])
        } catch (e) {
            this.msgWrapper.create(msg, {}, 'error');
            this.logger.error(e.stack);
            throw new Error('起飞时出现错误');
        }
        this.msgWrapper.create('已起飞', {}, 'success');
    }
}

export const QuickFlyBtnHandlerKey = Symbol('QuickFlyBtnHandlerKey') as InjectionKey<QuickFlyBtnHandler>
