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: any[] = [];

    constructor(
        private readonly logger: Logger,
    ) {
    }

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

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