import {IEditorInputFactoryRegistry, IFileInputFactory, IEditorInputFactory, ServicesAccessor} from '../../interfaces/editor/editor';

export class EditorInputFactoryRegistry implements IEditorInputFactoryRegistry {
    private instantiationService: any;
    private fileInputFactory: IFileInputFactory;
    private editorInputFactoryConstructors: { [editorInputId: string]: any } = Object.create(null);
    private readonly editorInputFactoryInstances: { [editorInputId: string]: IEditorInputFactory } = Object.create(null);

    public start(accessor: ServicesAccessor): void {
        // this.instantiationService = accessor.get(IInstantiationService);

        for (let key in this.editorInputFactoryConstructors) {
            const element = this.editorInputFactoryConstructors[key];
            this.createEditorInputFactory(key, element);
        }

        this.editorInputFactoryConstructors = Object.create(null);
    }

    private createEditorInputFactory(editorInputId: string, ctor: any): void {
        const instance = this.instantiationService.createInstance(ctor);
        this.editorInputFactoryInstances[editorInputId] = instance;
    }

    public registerFileInputFactory(factory: IFileInputFactory): void {
        this.fileInputFactory = factory;
    }

    public getFileInputFactory(): IFileInputFactory {
        return this.fileInputFactory;
    }

    public registerEditorInputFactory(editorInputId: string, ctor: any): void {
        if (!this.instantiationService) {
            this.editorInputFactoryConstructors[editorInputId] = ctor;
        } else {
            this.createEditorInputFactory(editorInputId, ctor);
        }
    }

    public getEditorInputFactory(editorInputId: string): IEditorInputFactory {
        return this.editorInputFactoryInstances[editorInputId];
    }
}
