import "reflect-metadata";
import Logger from "../class/Logger";
import globVars from "../globVars";
import { Container } from "../container/Container";

export default function EntryPoint(Index: ClassType<{}> & { main: () => void }) {
    const logger = Logger.factory(Index);
    if (window.WHTRANS) {
        logger.warn('退出, 已运行次数' + window.WHTRANS)
    } else {
        window.WHTRANS = window.WHTRANS === undefined ? 1 : window.WHTRANS++;

        let started = false;
        const starter = () => {
            console.log('starter init...');
            let started = performance.now();
            try {
                Container.setLogger(Container.factory(Logger))
                Index.main()
            } catch (e) {
                logger.error('加载出错: ' + e.stack || e.message);
            }
            let runTime: number = (performance.now() - started) | 0;
            globVars.loadTime = runTime;
            logger.info(`芜湖脚本完成加载, 耗时${ runTime }ms`);
        };
        const evHandler = () => {
            if (!started && (document.readyState === 'complete' || document.readyState === 'interactive')) {
                document.removeEventListener('readystatechange', evHandler);
                started = !started;
                starter();
            } else if (!(document.readyState === 'complete' || document.readyState === 'interactive')) {
                document.addEventListener('readystatechange', evHandler);
            }
        };
        evHandler();
    }
}
