import ClassName from "../container/ClassName"
import { Injectable } from "../container/Injectable"
import IFeature from "../man/IFeature"
import LocalConfigWrapper from "../class/LocalConfigWrapper"
import CommonUtils from "../class/utils/CommonUtils"
import Global from "../class/Global"
import ActionButtonUtils from "../class/utils/ActionButtonUtils"
import Logger from "../class/Logger"
import Alert from "../class/utils/Alert"
import Device from "../enum/Device"
import ATTACK_HELPER_CSS from "../../static/css/attack_helper.module.css"
import ATK_PAGE_REG from "./url/ATK_PAGE_REG";

enum FIGHT_STAGE {
    READY = 'ready',
    IN_PROGRESS_OR_ERROR = 'in_progress_or_error',
    FINISHED = 'finished',
    END = 'end',
    OTHER = 'other'
}

@ClassName('Atk')
@Injectable()
export default class Atk implements IFeature {

    private currentStage: FIGHT_STAGE = FIGHT_STAGE.OTHER;

    constructor(
        private readonly actionButtonUtils: ActionButtonUtils,
        private readonly localConfigWrapper: LocalConfigWrapper,
        private readonly commonUtils: CommonUtils,
        private readonly global: Global,
        // private readonly mathUtils: MathUtils,
        // private readonly fetchUtils: FetchUtils,
        private readonly logger: Logger,
    ) {
    }

    urlIncludes(): RegExp[] {
        return [ATK_PAGE_REG]
    }

    urlExcludes(): RegExp[] {
        return []
    }

    description(): string {
        return '攻击助手'
    }

    iStart(): void | Promise<void> {
        // 光速刷新按钮
        this.actionButtonUtils.add('光速刷新', () => this.doAttackReload());

        new MutationObserver((_, observer) => {
            let btnList = document.querySelectorAll('div[class^="dialogButtons___"] button') as NodeListOf<HTMLButtonElement>;

            if (btnList.length === 0) {
                if (this.currentStage === FIGHT_STAGE.READY && this.localConfigWrapper.config.quickFinishAtt === 3) {
                    document.body.classList.remove('wh-move-btn');
                    this.logger.info('移除body class wh-move-btn');
                    observer.disconnect();
                }
                // 错误或正在打
                this.currentStage = FIGHT_STAGE.IN_PROGRESS_OR_ERROR;
                this.logger.info('[attackHelper] currentStage', this.currentStage);
                return;
            }
            btnList.forEach(btn => {
                let btnText = btn.innerText.toLowerCase();
                if (btnText.includes('start') || btnText.includes('join')) {
                    // 开始
                    this.quickStartFight();
                } else if (btnText.includes('continue')) {
                    // 结束end
                    this.currentStage = FIGHT_STAGE.END;
                    observer.disconnect();
                } else if (btnText.includes('leave')) {
                    // 无意识状态FINISHED
                    this.quickFinishFight(btnList);
                }
                this.logger.info('[attackHelper] currentStage', this.currentStage);
            })
        })
            .observe(document.querySelector('#react-root'), { childList: true, subtree: true });
    }

    // 战斗页面快速刷新
    private doAttackReload(): void {
        if (!window.ReactDOM) {
            new Alert('光速刷新失败：未找到React对象');
            this.logger.error('光速刷新失败：未找到React对象');
            return;
        }
        if (!document.querySelector('#react-root #attacker')) {
            this.logger.error('dom元素未找到selector: [#react-root #attacker]');
            return;
        }
        let script = document.querySelector('script[src*="/builds/attack/"]');
        let url = script.src;
        if (!url.contains(/runtime\..+\.js/)) {
            this.logger.error('脚本源[' + url + '] 不匹配规则');
            return;
        }
        window.ReactDOM.unmountComponentAtNode(document.querySelector('#react-root'));
        script.remove();
        let node = document.createElement('script');
        node.src = url;
        node.type = 'text/javascript';
        document.head.appendChild(node);
    }

    // 光速拔刀
    private quickStartFight(): void {
        if (this.currentStage === FIGHT_STAGE.READY) {
            return;
        } else {
            this.currentStage = FIGHT_STAGE.READY;
        }
        if (this.localConfigWrapper.config.quickAttIndex === 6) return;
        /**
         * pc     #defender
         * mobile #attacker
         */
        const btn = <HTMLInputElement>(document.querySelector('#attacker button') || document.querySelector('#defender button'));
        this.logger.info('操作按钮', { btn });
        if (!btn.innerText.toLowerCase().includes('fight')) {
            this.logger.info('未找到攻击按钮, 光速拔刀跳过');
            new Alert('未找到攻击按钮, 光速拔刀跳过');
        } else {
            // 判断是否存在脚踢
            const hasKick = !!document.querySelector('#weapon_boots');
            // modal层
            // const modal: HTMLElement = document.querySelector('div[class^="modal___"]');
            let device = this.global.device;
            this.logger.info(`当前设备类型是${ device }`);
            // 区分设备
            switch (device) {
                case Device.PC: {
                    this.logger.info(`开始调整按钮位置`);
                    // 隐藏modal层
                    // modal.style.display = 'none';
                    // 根据选择的武器调整css
                    let css_top = '0';
                    switch (this.localConfigWrapper.config.quickAttIndex) {
                        // weapon_second
                        case 1: {
                            css_top = '97px';
                            break;
                        }
                        // weapon_melee
                        case 2: {
                            css_top = '194px';
                            break;
                        }
                        // weapon_temp
                        case 3: {
                            css_top = '291px';
                            break;
                        }
                        // weapon_fists
                        case 4:
                        // weapon_boots
                        case 5: {
                            css_top = '375px';
                            break;
                        }
                    }
                    this.commonUtils.styleInject(ATTACK_HELPER_CSS);
                    CommonUtils.addStyle(`.wh-move-btn #defender div[class^="modal___"]{top: ${ css_top };}`);
                    document.body.classList.add('wh-move-btn');
                    break;
                }
                case Device.MOBILE: {
                    this.logger.info(`开始调整按钮位置`);
                    // 加入css
                    let css_top = '0';
                    let slot_height = '76px';
                    // 判断有没有脚踢
                    if (hasKick) {
                        // 根据选择的武器调整
                        switch (this.localConfigWrapper.config.quickAttIndex) {
                            case 1: { // weapon_second
                                css_top = '76px';
                                break;
                            }
                            case 2: { // weapon_melee
                                css_top = '152px';
                                break;
                            }
                            case 3: { // weapon_temp
                                css_top = '228px';
                                break;
                            }
                            case 4: { // weapon_fists
                                css_top = '304px';
                                break;
                            }
                            case 5: { // weapon_boots
                                css_top = '380px';
                                break;
                            }
                        }
                    } else {
                        const slot = document.querySelector('#weapon_main') as HTMLElement;
                        const height = slot.offsetHeight + 1;
                        // TODO 待验证
                        slot_height = height + 'px';
                        // 根据选择的武器调整
                        switch (this.localConfigWrapper.config.quickAttIndex) {
                            case 1: { // weapon_second
                                css_top = `${ height }px`;
                                break;
                            }
                            case 2: { // weapon_melee
                                css_top = `${ height * 2 }px`;
                                break;
                            }
                            case 3: { // weapon_temp
                                css_top = `${ height * 3 }px`;
                                break;
                            }
                            case 4: { // weapon_fists
                                css_top = `${ height * 4 }px`;
                                break;
                            }
                            case 5: { // weapon_boots
                                css_top = `${ height * 5 }px`;
                                break;
                            }
                        }
                    }
                    const css_rule = ATTACK_HELPER_CSS.replace('CSSVAR', css_top).replace('CSSVAR', slot_height);

                    this.commonUtils.styleInject(css_rule);
                    document.body.classList.toggle('wh-move-btn');
                    btn.onclick = () => {
                        if (this.localConfigWrapper.config.quickFinishAtt !== 3) {
                            btn.remove();
                            // 停止自动刷新
                            // stop_reload = true;
                        } else {
                            document.body.classList.toggle('wh-move-btn');
                        }
                    };
                    break;
                }
                case Device.TABLET: {
                    break;
                }
            }
        }
    }

    // 光速跑路
    private quickFinishFight(btnList: NodeListOf<HTMLButtonElement>): void {
        if (this.currentStage === FIGHT_STAGE.FINISHED) {
            return;
        } else {
            this.currentStage = FIGHT_STAGE.FINISHED;
        }
        if (this.localConfigWrapper.config.quickFinishAtt === 3) {
            document.body.classList.remove('wh-move-btn');
            this.logger.info('移除body class wh-move-btn');
            return;
        }
        const user_btn_select = ['leave', 'mug', 'hosp'][this.localConfigWrapper.config.quickFinishAtt];
        // const wrap = document.querySelector('#react-root');
        this.logger.info('光速跑路选项选中：', user_btn_select);
        //     const btn_arr: HTMLButtonElement[] = document.querySelectorAll('div[class^="dialogButtons___"] button') as unknown as HTMLButtonElement[];
        if (btnList.length > 1) btnList.forEach(btn => {
            const flag = btn.innerText.toLowerCase().includes(user_btn_select);
            this.logger.info('按钮内容：', btn.innerText, '，是否包含选中：', flag);
            if (!flag) btn.style.display = 'none';
        });
    }

}
