import { IConfiguration, IConfigurationTransitionEffect, IConfigurator } from './interfaces/configurator.interface';
import { EventObservableTypes } from './interfaces/event-observable.interface';
import { IViewerCommunicator, IPostMessageOrigin } from './interfaces/viewer-communicator.interface';

export class Configurator implements IConfigurator {
    private comm: IViewerCommunicator;
    constructor(comm: IViewerCommunicator) {
        this.comm = comm;
    }

    async preloadConfigurator(config: IConfiguration, delay?: number) {
        await this.comm.onModelLoaded();
        this.comm.sendToViewer({
            action: 'configuratorPreload',
            data: [config, delay],
            to: IPostMessageOrigin.WORKER
        });
    }

    async setConfigurator(config: Array<IConfiguration>) {
        await this.comm.onModelLoaded();
        this.comm.sendToViewer({
            action: 'setConfigurator',
            data: [config],
            to: IPostMessageOrigin.WORKER
        });
    }

    async toggleConfiguratorUI(state: boolean) {
        await this.comm.onModelLoaded();
        this.comm.sendToViewer({
            action: 'toggleConfiguratorUI',
            data: [state],
            to: IPostMessageOrigin.WORKER
        });
    }

    async selectConfigurator(index: number) {
        return new Promise(async (resolve: any, reject: any) => {
            await this.comm.onModelLoaded();
            this.comm.eventObservable.add(EventObservableTypes.ON_CONFIGURATOR_SELECT_DONE, resolve);
            this.comm.sendToViewer({
                action: 'onConfiguratorSelect',
                data: [index],
                to: IPostMessageOrigin.WORKER
            });
        });
    }

    async setConfiguratorEffect(effect: IConfigurationTransitionEffect) {
        await this.comm.onModelLoaded();
        this.comm.sendToViewer({
            action: 'setConfiguratorEffect',
            data: [effect],
            to: IPostMessageOrigin.WORKER
        });
    }
}