import NNB_INFO_HTML from "../../../static/html/nnb_info.html";
import Popup from "../utils/Popup";
import ClassName from "../../container/ClassName";
import { Injectable } from "../../container/Injectable";
import TornPDAUtils from "../utils/TornPDAUtils";

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

    constructor(
        private readonly tornPDAUtils: TornPDAUtils,
    ) {
    }

    public handle(): void {
        const insert = NNB_INFO_HTML
            .replace('{{}}', localStorage.getItem('APIKey') || '不可用')
            .replace('{{}}', this.tornPDAUtils.isPDA() ? this.tornPDAUtils.APIKey : '不可用');
        const popup = new Popup(insert, '查看NNB').element;
        const select = popup.querySelector('input');
        const node = popup.querySelector('p');
        popup.querySelector('button').addEventListener('click', ev => {
            let target = ev.target as HTMLInputElement;
            target.style.display = 'none';
            node.innerHTML = '加载中';
            // API 计算
            if (select.checked) {
                const api_key = this.tornPDAUtils.isPDA() ? this.tornPDAUtils.APIKey : window.localStorage.getItem('APIKey');
                window.fetch(`https://api.torn.com/user/?selections=bars,perks&key=${ api_key }`)
                    .then(res => res.json())
                    .then(data => {
                        if (data['error']) {
                            node.innerHTML = `出错了 ${ JSON.stringify(data['error']) }`;
                            target.style.display = null;
                            return;
                        }
                        let nb = data['nerve']['maximum'];
                        let perks = 0;
                        Object.values(data).forEach(val => {
                            (val instanceof Array) && val.forEach(s => {
                                s = s.toLowerCase();
                                s.includes('maximum nerve') && (perks += (<any>new RegExp('[0-9].').exec(s))[0] | 0)
                            })
                        });
                        node.innerHTML = `NNB: ${ nb - perks }`;
                        target.style.display = null;
                    });
            }
            // 主页计算
            else {
                if (window.location.href.includes('index.php') && document.title.includes('Home')) {
                    let nb = (<any>document.querySelector('#barNerve p[class^="bar-value___"]').innerText.split('/')[1]) | 0;
                    let perks = 0;
                    document.querySelectorAll('#personal-perks li').forEach(elem => {
                        const str = elem.innerText.toLowerCase();
                        str.includes('maximum nerve') && (perks += (/[0-9]./.exec(str) as any)[0] | 0)
                    });
                    node.innerHTML = `NNB: ${ nb - perks }`;
                    target.style.display = null;
                    return;
                }
                node.innerHTML = '不在主页面，<a href="/index.php">点击前往</a>';
                target.style.display = null;
            }
        });
    }
}
