import { _decorator, CachedArray, Component } from 'cc';
import { EventsType, IExitHandler, IEventHandler } from '../../interface/IPrimary';
const { ccclass } = _decorator;

export class EventDataNew
{
    public type: EventsType;
    public onComplete: (evtType: EventsType) => void;
}

@ccclass('EventsManagerNew')
export class EventsManagerNew extends Component
{
    public static eventsArrayNew: Array<EventDataNew>;

    static
    {
        EventsManagerNew.eventsArrayNew = new Array<EventDataNew>();
    }

    public static fn_AttachNewEvent<T>(evtType: EventsType, obj: IEventHandler)
    {
        let method = (evtType) => obj.fn_Execute(evtType);

        let data = new EventDataNew();
        data.type = evtType;
        data.onComplete = method;

        EventsManagerNew.eventsArrayNew.push(data);
    }

    public static fn_DetachEvent(evtType: EventsType)
    {
        let index = EventsManagerNew.eventsArrayNew.findIndex(data => data.type == evtType);
        if (index != -1)
            EventsManagerNew.eventsArrayNew.splice(index, 1);
    }

    public static fn_DetachEvents()
    {
        EventsManagerNew.eventsArrayNew.splice(0, EventsManagerNew.eventsArrayNew.length); // double check
    }
    
    public static fn_FireEvent(evtType: EventsType)
    {
        let eventData = EventsManagerNew.fn_FindEventBasedOnType(evtType);

        if (eventData == null) 
        {
            return;
        }

        eventData.onComplete(evtType);
    }

    public static fn_FindEventBasedOnType(evtType: EventsType) : EventDataNew
    {
        return EventsManagerNew.eventsArrayNew.find(evt => evt.type == evtType);
    }
}
