import Alert from "../../class/utils/Alert";
import InfoUtils from "../../class/utils/InfoUtils";
import Popup from "../../class/utils/Popup";
import { Container } from "../../container/Container";
import Logger from "../../class/Logger";

// 守望者
export default function safeKeeper() {
    let infoUtils = Container.factory(InfoUtils);
    let logger = Container.factory(Logger);

    let url = `https://www.torn.com/loader.php?sid=attackData&mode=json&step=poll&user2ID=`;
    let popup = new Popup('<p>监测目标ID玩家的防御状态，找出隐身攻击者</p>', '守望者 (测试中)');
    let p = document.createElement('p');
    let uid: HTMLInputElement = document.createElement('input');
    let start = document.createElement('button');
    let stop = document.createElement('button');
    let self_target = document.createElement('button');
    let attackers: MyHTMLElement = document.createElement('div');
    attackers.obj = {};
    let records: MyHTMLElement = document.createElement('div');
    records.list = [];
    records.details = {};
    // interval loop_id
    let loop_id = null;
    let updateAttackersDOM = function () {
        let html = '进攻者：<br/>';
        Object.keys(attackers.obj).forEach(id => html += `[${ id }]<br/>`);
        attackers.innerHTML = html;
    };
    let updateRecordsDOM = function () {
        let html = '战斗记录：<br/>';
        records.list.forEach(rid => {
            let { TimeCreated, attackID, attackerID, attackerItemID, result, text } = records.details[rid];
            html += `[${ TimeCreated }] [${ attackerID }] [${ attackerItemID }] ${ result } ${ text }<br/>`;
        });
        records.innerHTML = html;
    };

    uid.type = 'text';
    uid.placeholder = '目标ID';
    start.innerHTML = '开启';
    stop.innerHTML = '关闭';
    stop.disabled = true;
    self_target.innerHTML = '填入自己';
    // 弹出窗口关闭时结束
    let popup_close = popup.close;
    popup.close = () => {
        if (loop_id === null) {
            popup.close = popup_close;
            popup.close();
        } else new Alert('守望者运行中，请先停止', { timeout: 2 });
    }

    popup.element.appendChild(p);
    popup.element.appendChild(uid);
    popup.element.appendChild(start);
    popup.element.appendChild(stop);
    popup.element.appendChild(self_target);
    popup.element.appendChild(attackers);
    popup.element.appendChild(records);

    start.addEventListener('click', () => {
        if (loop_id !== null || !uid.value) return;
        start.disabled = true;
        stop.disabled = false;
        uid.readOnly = true;
        p.innerHTML = '状态：已开 ✅';
        let count = 0;
        loop_id = window.setInterval(async () => {
            // 记录当前循环的id
            let that_id = loop_id;
            let res = await (await window.fetch(url + uid.value, {
                headers: { 'X-Requested-With': 'XMLHttpRequest' },
                referrer: "loader.php?sid=attack&user2ID=" + uid.value
            })).text();
            if (loop_id !== that_id) return;
            let data = JSON.parse(res.split('<div')[0]);
            logger.info(count++, data);
            let { DB, currentFightStatistics, histLog } = data;
            // 攻击人
            // 格式：currentFightStatistics = {uid: {...}, uid2: {...}}
            Object.keys(currentFightStatistics || {}).forEach(id => {
                if (id === uid.value) return;
                if (!attackers.obj[id]) {
                    attackers.obj[id] = true;
                    updateAttackersDOM();
                }
            });
            // 攻击历史
            (DB['currentFightHistory'] || []).forEach(record => {
                if (records.list.includes(record['ID'])) return;
                let { ID, TimeCreated, attackID, attackerID, attackerItemID, result, text } = record;
                records.list.push(ID);
                records.details[ID] = { TimeCreated, attackID, attackerID, attackerItemID, result, text };
                updateRecordsDOM();
            });
            // 攻击历史日志
            if (histLog && histLog[uid.value]) histLog[uid.value].forEach(log => {
                if (records.list.includes(log['ID'])) return;
                let { ID, TimeCreated, attackID, attackResult, userID } = log;
                records.list.push(ID);
                records.details[ID] = {
                    TimeCreated,
                    attackID,
                    attackerID: userID,
                    attackerItemID: 0,
                    result: attackResult,
                    text: ''
                };
                updateRecordsDOM();
            });
        }, 900);
    });

    stop.addEventListener('click', () => {
        if (loop_id === null) return;
        start.disabled = false;
        stop.disabled = true;
        uid.readOnly = false;
        window.clearInterval(loop_id);
        loop_id = null;
        p.innerHTML = '状态：已关 ❎';
    });
    self_target.addEventListener('click', () => uid.value = (infoUtils.getPlayerInfo()['userID']) + '');
}
