import POPUP_HTML from "../../../static/html/popup.html";
import { Container } from "../../container/Container";
import Global from "../Global";
import Logger from "../Logger";
import globVars from "../../globVars";

/**
 * 弹窗
 */
export default class Popup {
    private readonly container: HTMLElement = null;
    private readonly node: HTMLElement = null;
    private onClosing: () => unknown;

    /**
     * 构造新弹窗
     * @param innerHTML
     * @param title
     * @param onClosing
     * @param global
     * @param logger
     */
    constructor(
        innerHTML: string,
        title: string = '芜湖助手',
        onClosing: () => unknown = () => {
        },
        private readonly global: Global = Container.factory(Global),
        private readonly logger: Logger = Container.factory(Logger),
    ) {
        this.onClosing = onClosing;
        if (globVars.popup_node) {
            this.logger.info('关闭前一个弹窗');
            globVars.popup_node.close();
        }
        this.logger.info('新建弹窗', { innerHTML, title });
        const popup = document.createElement('div');
        popup.id = 'wh-popup';
        popup.innerHTML = POPUP_HTML.replace('{{}}', title).replace('{{}}', innerHTML);
        document.body.append(popup);
        popup.addEventListener('click', e => {
            e.stopImmediatePropagation();
            if (e.target === popup) this.close();
        });
        this.container = popup;
        this.node = popup.querySelector('#wh-popup-cont');
        this.hideChat();
        globVars.popup_node = this;
    }

    public close() {
        this.onClosing();
        this.container.remove();
        this.showChat();
    }

    public get element(): HTMLElement {
        return this.node;
    }

    /**
     * @return {HTMLElement} id=wh-popup-cont
     * @deprecated
     * 使用element替代
     */
    public getElement(): HTMLElement {
        return this.node;
    }

    private hideChat() {
        document.querySelector('#chatRoot').classList.add('wh-hide');
    }

    private showChat() {
        document.querySelector('#chatRoot').classList.remove('wh-hide');
    }

    // 禁止单例调用
    private getInstance() {
    }

    public setOnClosing(onClosing): void {
        if (!onClosing) {
            throw new Error('无方法用于设置onClosing');
        }
        this.onClosing = onClosing;
    }

    public closing(func: () => unknown): Popup {
        this.setOnClosing(func);
        return this;
    }
}
