

export default class EventRegister {

    static _Single;

    static Get() {
        if (this._Single == null || this._Single == undefined) {
            this._Single = new EventRegister();
        }

        return this._Single;
    }   

    constructor() {

        this.Events = [
            "OnAuthChange",
            "OnItemsChange_Main",
            "OnItemsChange_Move"
        ];
        this.Listeners = {};

        this.Events.map(function (event) {
            this.Listeners[event] = [];
        }.bind(this));
    }


    RegisterListener(Event, control) {
        if (!this.Events.includes(Event))
            throw "Event not found";

        if (control["Event_" + Event] == undefined)
            throw "Control not implement event function";

        this.Listeners[Event].push(control);

        //Флаг используется в BaseControl, 
        //чтобы при уничтожении контрола 
        //инициировать удаление из EventRegister listeners
        control.IsEventListener = true;
    }

    UnregistListener(control) {

        Object.keys(this.Listeners).map(function (e) {
            let pos = this.Listeners[e].findIndex(e2 => e2.ID === control.ID);
            if (pos != -1) {
                this.Listeners[e].splice(pos, 1);
            }
        }.bind(this));
    }

    EventAction(Event, params) {

        if (!this.Events.includes(Event))
            throw "Event not found";

        this.Listeners[Event].map(function (e) {
            e["Event_" + Event](params);
        });
    }

}