import { v4 } from 'uuid'
import { EventKey, EventMessage } from './interface'

/**
 * 事件总线
 */
export default new (class {
    private eventMap = new Map<string, EventMessage>();

    /** 订阅事件 */
    $on(eventKey: keyof typeof EventKey | (keyof typeof EventKey)[], callback: EventMessage['callback']) {
        const uuid = v4();
        const keys = Array.isArray(eventKey) ? eventKey : [eventKey];

        this.eventMap.set(uuid, {
            keys,
            callback
        })

        /** 销毁事件，注意离开页面时要手动销毁当前页面订阅的事件，防止事件重复触发 */
        return {
            uuid,
            cancel: () => this.eventMap.delete(uuid)
        }
    }

    /** 触发事件 */
    $emit(eventKey: keyof typeof EventKey, data?: unknown) {
        for (const message of this.eventMap.values()) {
            if (message.keys.includes(eventKey)) {
                message.callback(data);
            }
        }
    }

    /** 取消事件 */
    $off(...eventkeys: (keyof typeof EventKey)[]) {
        if (eventkeys.length) {
            for (const [uuid, message] of this.eventMap.entries()) {
                for (let i = message.keys.length - 1; i >= 0; i--) {
                    if (eventkeys.includes(message.keys[i])) {
                        message.keys.splice(i, 1);
                    }
                }
                if (!message.keys.length) {
                    this.eventMap.delete(uuid);
                }
            }
        } else {
            this.eventMap.clear();
        }
    }
})