import XUNZHAOMUZHUANG_HTML from "../../../static/html/xunzhaomuzhuang/index.html";
import * as MUZHUANG_ID_LIST_JSON from "../../../static/json/muzhuang_id_list.json";
import CommonUtils from "../utils/CommonUtils";
import XUNZHAOMUZHUANG_CSS from "../../../static/css/xunzhaomuzhuang.module.css";
import TornStyleBlock from "../utils/TornStyleBlock";
import MathUtils from "../utils/MathUtils";
import FetchUtils from "../utils/FetchUtils";
import ClassName from "../../container/ClassName";
import { Injectable } from "../../container/Injectable";
import IFeature from "../../man/IFeature";

/**
 * 寻找木桩
 * /item.php?temp=4#xunzhaomuzhuang
 */
@ClassName('XZMZ')
@Injectable()
export default class XZMZ implements IFeature {
    description(): string {
        return "寻找木桩";
    }

    iStart(): void | Promise<void> {
        this.start()
    }

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

    urlIncludes(): RegExp[] {
        return [/item.php\?temp=4/];
    }

    start() {
        let hasInit: boolean = false
        let handle = () => {
            if (!hasInit && window.location.hash === '#xunzhaomuzhuang') {
                this.init()
                hasInit = true
            }
        }
        window.addEventListener('hashchange', handle)
        handle()
    }

    private mainRoleContainer: HTMLElement;
    private IDList: number[];
    private btn: HTMLButtonElement;
    private stopBtn: HTMLButtonElement;
    private stopSignal: boolean = false;
    private tips: HTMLElement;
    private counter: number;

    public constructor(
        private readonly mathUtils: MathUtils,
        private readonly commonUtils: CommonUtils,
        private readonly fetchUtils: FetchUtils,
    ) {
    }

    public init() {
        this.commonUtils.styleInject(XUNZHAOMUZHUANG_CSS);
        document.body.classList.add('wh-hide-title');
        document.title = document.title.replace('Items', '寻找木桩');
        this.mainRoleContainer = document.querySelector('div[role="main"]');
        let block = new TornStyleBlock('寻找木桩');
        block.setContent(XUNZHAOMUZHUANG_HTML);
        this.mainRoleContainer.append(block.getBase());
        this.IDList = MUZHUANG_ID_LIST_JSON.default;
        this.btn = block.querySelector('#deadman-start-btn') as HTMLButtonElement;
        this.stopBtn = this.btn.nextElementSibling as HTMLButtonElement;
        this.tips = block.querySelector('#deadman_tips');

        this.btn.addEventListener('click', () => {
            this.mainRoleContainer.querySelector('#table-body').innerHTML = '';
            this.btn.disabled = true;
            this.stopSignal = false;
            this.StartSearch();
        });
        this.stopBtn.addEventListener('click', () => this.stopSignal = true);
    }

    private StartSearch() {
        this.counter = this.IDList.length;
        const tips = this.tips;
        tips.innerText = "---寻找中,长按目标名字弹出迷你档案---";
        window.setTimeout(async () => {
            for (const id of this.IDList) {
                if (this.stopSignal) {
                    this.stopSignal = false;
                    this.counter = 1;
                    this.counterHandler(false);
                    return;
                }
                await this.SearchDeadman(id);
            }
        }, 1);
    }

    private async SearchDeadman(id) {
        this.fetchUtils.getProfile(id).then((res) => {
            if (res.userStatus.status.type === 'ok') {
                this.addRow({
                    player_id: res.user.userID,
                    name: res.userInformation.name,
                    level: res.userInformation.level
                });
            }
        });
        await this.commonUtils.sleep(this.mathUtils.getRandomInt(100, 200));
    }

    private addRow(data) {
        let $parentNode = this.mainRoleContainer.querySelector('#table-body'),
            $node = '<tr data-id="' + data.player_id + '"></tr>';
        $node += '<td style="border: 1px solid darkgray;padding:5px;text-align:center;">' + data.player_id + '</td>'
        $node += `<td style="border: 1px solid darkgray;padding:5px;text-align:center;"><a href="/profiles.php?XID=${ data.player_id }">${ data.name }</a></td>`;
        $node += '<td style="border: 1px solid darkgray;padding:5px;text-align:center;">' + data.level + '</td>'
        $node += '<td style="border: 1px solid darkgray;padding:5px;text-align:center;"><a href="https://www.torn.com/loader.php?sid=attack&user2ID=' + data.player_id + '" target="_blank" class="torn-btn">攻击</a></td>'
        $parentNode.insertAdjacentHTML('beforeend', $node)
    }

    private counterHandler(hasCoolDown: boolean = true): void {
        this.counter--;
        if (this.counter === 0) {
            this.tips.innerText = "---寻找结束,等待60秒后重试---";
            let countdown = hasCoolDown ? 60 : 2;
            let timer = window.setInterval(() => {
                this.btn.innerHTML = (countdown--).toString();
                if (countdown === 0) {
                    window.clearInterval(timer);
                    this.btn.disabled = false;
                    this.btn.innerHTML = '重新寻找';
                }
            }, 1000);
        }
    }
}