import ClassName from "../container/ClassName";
import { Injectable } from "../container/Injectable";
import IFeature from "../man/IFeature";
import LocalConfigWrapper from "../class/LocalConfigWrapper";
import CommonUtils from "../class/utils/CommonUtils";
import QUICK_CRIMES_HTML from "../../static/html/quick_crimes.html";

@ClassName('CrimePageModifier')
@Injectable()
export default class CrimePageModifier implements IFeature {
    constructor(
        private readonly localConfigWrapper: LocalConfigWrapper
    ) {
    }

    description(): string {
        return "页面快速crime";
    }

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

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

    urlIncludes(): RegExp[] {
        return [/crimes\.php/];
    }

    start() { // TODO 重构、与翻译解藕
        if (this.localConfigWrapper.config.quickCrime) {
            // iframe
            if (self !== top) {
                const isValidate = document.querySelector('h4#skip-to-content').innerText.toLowerCase().includes('validate');
                CommonUtils.elementReady('#header-root').then(e => e.style.display = 'none');
                CommonUtils.elementReady('#sidebarroot').then(e => e.style.display = 'none');
                CommonUtils.elementReady('#chatRoot').then(e => e.style.display = 'none');
                if (!isValidate) document.body.style.overflow = 'hidden';
                CommonUtils.elementReady('.content-wrapper').then(e => {
                    e.style.margin = '0px';
                    e.style.position = 'absolute';
                    e.style.top = '-35px';
                });
                CommonUtils.elementReady('#go-to-top-btn button').then(e => e.style.display = 'none');
            }
            const element = document.querySelector('.content-wrapper');
            const OB = new MutationObserver(() => {
                OB.disconnect();
                trans();
                OB.observe(element, {
                    characterData: true,
                    attributes: true,
                    subtree: true,
                    childList: true
                });
            });
            const trans = () => {
                const dom = QUICK_CRIMES_HTML;
                const hasInserted = element.querySelector('.wh-translate') !== null;
                const $title = document.querySelector('div.content-title');
                const $info = document.querySelector('.info-msg-cont');
                if (!hasInserted) {
                    if ($title) $title.insertAdjacentHTML('beforebegin', dom);
                    else if ($info) $info.insertAdjacentHTML('beforebegin', dom);
                }
            };
            trans();
            OB.observe(element, {
                characterData: true,
                attributes: true,
                subtree: true,
                childList: true
            });
        }
    }
}
