import Logger from "./Logger";
import { Container } from "../container/Container";
import ClassName, { GetClassName } from "../container/ClassName";
import { Injectable } from "../container/Injectable";

@ClassName('ModuleLoader')
@Injectable()
export default class ModuleLoader {
    private readonly classes: (new(...arg: any) => { init: () => void })[] = [];
    private readonly logger = Logger.factory(ModuleLoader)

    // constructor() {
    // }

    /**
     *
     * @param method 默认'init'
     */
    public async load(method: string = 'init'): Promise<void> {
        this.logger.info('即将加载: ', this.classes)
        this.classes.forEach(clazz => {
            try {
                this.logger.info('正在加载' + GetClassName(clazz))
                Container.factory(clazz)[method]();
            } catch (e) {
                this.logger.error('加载[' + GetClassName(clazz) + ']时出错', e.message, e.stack);
            }
        });
        this.classes.length = 0;
    }

    public push(clazz: new(...arg: any) => { init: () => void }): void {
        this.classes.push(clazz);
    }
}
