import { isSsr } from '@newland/toubiz-widget/src/env';

class ComponentRegistryProxy {

    constructor() {
        this.locked = false;
        this.componentsToReplace = {};
        this.componentsToRegister = {};
    }

    registerComponent(componentName, component) {
        if (this.isLocked) {
            throw new Error(
                'ComponentRegistryProxy is already locked. You must register components before toubiz widget is initialized.'
            );
        }
        this.componentsToRegister[componentName] = component;
    }

    replaceComponent(componentName, component) {
        if (this.isLocked) {
            throw new Error(
                'ComponentRegistryProxy is already locked. You must register components before toubiz widget is initialized.'
            );
        }
        this.componentsToReplace[componentName] = component;
    }

    apply(componentRegistry) {
        for (const [ name, component ] of Object.entries(this.componentsToRegister)) {
            componentRegistry.registerComponent(name, component);
        }
        for (const [ name, component ] of Object.entries(this.componentsToReplace)) {
            componentRegistry.replaceComponent(name, component);
        }
    }
}

let registry = new ComponentRegistryProxy();

// The proxy will be compiled in a completely different webpack context
// thus, the only way of sharing a single instance between multiple
// contexts is to assign it to a global variable.
if (!isSsr()) {
    if (!window._componentRegistryProxy) {
        window._componentRegistryProxy = new ComponentRegistryProxy();
    }
    registry = window._componentRegistryProxy;
}

export default registry;
