/*
 * @Author: thy
 * @Date: 2023-11-28 18:09:11
 * @LastEditors: thy
 * @LastEditTime: 2023-12-01 12:15:31
 * @Description: file content
 * @FilePath: \dsk-operate-ui\src\utils\postMessageBridge\bridge\eventCenter.js
 */

import { v4 } from "uuid";
import { normalToPromise } from "@/utils/postMessageBridge/tools";
import chalk from "@alita/chalk";
window.alitadebug = true;

/**
 * 事件回调 调度中心
 */
class EventCenter {
  //事件回调储存栈
  _eventHandlerMap = new Map();
  _vueIns = null;
  constructor(vueIns) {
    vueIns ? this._vueIns = vueIns : null;
    process.env.ENV != "production" ? chalk.ready(chalk.bgGreen("事件调度中心初始化完毕")) : null;
  }

  /**
   * 根据回调ID获取事件回调储存中的回调
   * @param {string} handlerId 
   */
  getTargetHandler(handlerId) {
    return this._eventHandlerMap.get(handlerId);
  }

  /**
   * 注册事件回调到 事件储存中
   * @param {Promise} promiseCallBack 
   */
  registerHandler(promiseCallBack) {
    return new Promise((resolve, reject) => {
      if (Object.prototype.toString.call(promiseCallBack) !== "[object Function]") return console.warn("传入的回调类型不是一个函数");
      const uid = v4();
      this._eventHandlerMap.set(uid, promiseCallBack);
      resolve(uid);
    });
  }

  /**
   * 根据回调ID卸载事件回调储存中的回调
   * @param {string} handlerId 
   */
  writeOffHandler(handlerId) {
    return this._eventHandlerMap.delete(handlerId);
  }

  /**
   * 根据回调ID 执行事件回调储存中的回调 并卸载
   * @param {string} handlerId 
   */
  executeHandler(handlerId, params = {}) {
    return new Promise((resolve, reject) => {
      try {
        const currentCallBack = this.getTargetHandler(handlerId);
        if (!currentCallBack) return reject("执行回调错误,未找到对应回调");
        // 缓存回调
        const cb = normalToPromise(currentCallBack);
        // 删除回调
        this._eventHandlerMap.delete(handlerId);
        // 执行回调
        resolve(cb(params));
      } catch (error) {
        console.log(error);
      }
    });
  }
}

export default EventCenter;