export class MessageEvent {
  event = {};
  on(type, callback) {
    if (!this.event[type]) {
      this.event[type] = [];
    }
    this.event[type].push(callback);
  }
  off(type, callback) {
    if (callback) {
      let index = this.event[type].indexOf(callback);
      if (index == -1) return;
      this.event[type].splice(index, 1);
    } else {
      this.event[type] = [];
    }
  }
  emit(type, e) {
    if (!this.event[type]) return;
    this.event[type].forEach(item => {
      item && item(e);
    });
  }
}

export class UnityMessageEvent extends MessageEvent {
  constructor() {
    super();
    if (window.vuplex) {
      window.vuplex.addEventListener('message', e => {
        console.log('============================getMessageForUnity============================');
        const data = JSON.parse(e.data);
        console.log(data);
        this.emit(data.type, data.message);

        // 将消息广播给子页面
        let iframeDom = document.getElementsByClassName('iframe');
        for (let i = 0; i < iframeDom.length; i++) {
          const item = iframeDom[i];
          item.contentWindow.postMessage(data.type, data.message);
        }
      });
    }
  }
  addEventListener(type, callback) {
    if (window.vuplex) {
      this.on(type, callback);
    } else {
      window[type] = callback;
    }
  }
  sendMsg(type, message) {
    if (window.parent) {
      window.parent.postMessage({ type, message });
    } else if (window.vuplex) {
      window.vuplex.postMessage({ type, message });
    }
  }
}

export class PageMessageEvent extends MessageEvent {
  constructor() {
    super();
    window.addEventListener('message', e => {
      if (typeof e.data == 'string') {
        try {
          const data = JSON.parse(e.data);
          if(data.type) {
            this.emit(data.type, data.message);
          }
        } catch (e) {
          console.error(e);
        }
      }
    });
  }

  sendMsg(type, message) {
    let data = JSON.stringify({
      type,
      message,
    });
    if (window.parent) {
      // 给父级发消息
      window.parent.postMessage(data, '*');
    } else {
      // 给子集广播消息
      let iframeDom = document.getElementsByClassName('iframe');
      for (let i = 0; i < iframeDom.length; i++) {
        const item = iframeDom[i];
        item.contentWindow.postMessage(data, '*');
      }
    }
  }
}
