import PRICE_WATCHER_HTML from "../../../static/html/price_watcher.html";
import Popup from "../utils/Popup";
import { Injectable } from "../../container/Injectable";
import ClassName from "../../container/ClassName";
import LocalConfigWrapper from "../LocalConfigWrapper";
import TornPDAUtils from "../utils/TornPDAUtils";

@Injectable()
@ClassName('ItemPriceWatcherHandler')
export default class ItemPriceWatcherHandler {

    constructor(
        private readonly localConfigWrapper: LocalConfigWrapper,
        private readonly tornPDAUtils: TornPDAUtils,
    ) {
    }

    public handle(): void {
        const watcher_conf = this.localConfigWrapper.config.priceWatcher;
        const pre_str = JSON.stringify(watcher_conf);
        const html = PRICE_WATCHER_HTML
            .replace('{{}}', localStorage.getItem('APIKey') || '不可用')
            .replace('{{}}', this.tornPDAUtils.isPDA() ? this.tornPDAUtils.APIKey : '不可用')
            .replace('{{}}', (watcher_conf['pt'] || -1).toString())
            .replace('{{}}', (watcher_conf['xan'] || -1).toString());
        const popup = new Popup(html, '价格监视设置');
        popup.getElement().querySelector('button').onclick = () => {
            const [pt_node, xan_node] = Array.from(<NodeListOf<HTMLInputElement>>popup.getElement().querySelectorAll('input[type="number"]'));
            watcher_conf.pt = (pt_node.value as any) | 0;
            watcher_conf.xan = (xan_node.value as any) | 0;
            if (JSON.stringify(watcher_conf) !== pre_str)
                this.localConfigWrapper.config.priceWatcher = watcher_conf;
            popup.close();
        };
    }
}
