import { setTimeout } from 'core-js';
import Stomp from 'stompjs'
import store from '../store/index'

export default class MessageBridge {
  observers;// 观察者
  calcSocket;// 后台websocket
  adapterSocket;// 适配器websocket
  flag;
  windFlag;
  flagArr;
  constructor() {
    this.register = this.register.bind(this);
    this.unregister = this.unregister.bind(this);
    this.onmessage = this.onmessage.bind(this);
    this.getActions = this.getActions.bind(this);
    this.observers = new Array();
    this.flagArr = new Array();
    this.flag = (new Date()).getTime();
    this.windFlag = (new Date()).getTime();
    // this.reconnect()
    this.calcSocket = new WebSocket(`ws://${process.env.VUE_APP_APIS}/wisdom_service`, this.onmessage, ["/topic/voice-control","/topic/attention","/topic/temperature-count"]);
      // "/topic/title-info","/topic/suggestion","/topic/fault-popup",
    this.adapterSocket = new WebSocket(`ws://${process.env.VUE_APP_ADAPTERURLS}/wisdom`, this.onmessage, ["/topic/windturbine", "/topic/pv"]);
  }

  /* 单例 */
  static getInstance() {
    if (!MessageBridge.instance) {
      MessageBridge.instance = new MessageBridge();
    }
    return MessageBridge.instance;
  }

  /* 获得消息 */
  onmessage(msg) {
    // if (msg.headers.destination === "/topic/title-info") {
    //   this.flag = (new Date()).getTime()
    // }
    // if (msg.headers.destination === "/topic/windturbine") {
    //   this.windFlag = (new Date()).getTime()
    // }
    if (msg.command != "MESSAGE" || !msg.headers.destination) return;
    let os = this.getActions(msg.headers.destination);
    for (let id in os) {
      try {
        os[id].action(msg.body, msg.headers);
      } catch (e) { }
    }
  }

  getActions(destination) {
    let list = new Array()
    if ((this.observers.filter(item => item.key === "/topic/windturbine").length === 0) || (this.observers.filter(item => item.key === "/topic/suggestion").length === 0) || (this.observers.filter(item => item.key === "/topic/title-info").length === 0)) {
      store.commit('observers', false)
    }
    for (let i in this.observers) {
      if (this.observers[i].key == destination) {
       if(list.filter(item => item.key  === this.observers[i].key).length <= 2 ) {
        list.push(this.observers[i]);
       }
      }
    }
    return list;
  }

  /* 注册消息 */
  register(msgs) {
    for (let i in msgs) {
      if (this.observers.filter(item => item.key === msgs[i].key).length <= 5) {
        this.observers.push(msgs[i]);
      }
    }
  }

  /* 取消注册消息 */
  unregister(msgs) {
    let showIndex = null
    let status = this.observers.filter(item => item.key === msgs.key).length
    if(status){
      this.observers.forEach((item, index) => {
        if (item.key === msgs.key) {
          showIndex = index
        }
      })
      this.observers.splice(showIndex, 1);
    }
  }

  // reconnect() {
  //   setTimeout(() => {
  //     if ((this.observers.filter(item => item.key === "/topic/windturbine").length === 0) || (this.observers.filter(item => item.key === "/topic/suggestion").length === 0) || (this.observers.filter(item => item.key === "/topic/title-info").length === 0)) {
  //       store.commit('observers', false)
  //     }
  //     this.reconnect()
  //   }, 10000);
  //   if (((new Date()).getTime() - this.windFlag) > 20000) {
  //     this.adapterSocket.disconnect()
  //     this.adapterSocket.connect()
  //   }
  //   if (((new Date()).getTime() - this.flag) > 20000) {
  //     this.calcSocket.disconnect()
  //     this.calcSocket.connect()
  //   }
  // }
}

class WebSocket {
  onmessage;
  url;
  settings;
  client;

  constructor(url, onmessage, settings) {
    this.onerror = this.onerror.bind(this);
    this.connectCallBackSubscribe = this.connectCallBackSubscribe.bind(this);
    this.send = this.send.bind(this);
    this.connect = this.connect.bind(this);
    this.disconnect = this.disconnect.bind(this);
    this.onmessage = onmessage;
    this.url = url;
    this.settings = settings;
    // this.MessageBridge = new MessageBridge()
    try {
      this.connect();
    } catch (e) {
      // console.log("websocket连接错误:\n" + e);
    }
  }

  /* 连接 */
  connect() {
    this.client = Stomp.client(this.url);
    this.client.connect("", "", this.connectCallBackSubscribe, this.onerror);
    this.client.debug = null;
  }

  disconnect() {
    this.client.disconnect()
  }

  /* 检测连接是否正常 */
  protector() {

  }

  /* 注册 */
  connectCallBackSubscribe() {
    // console.log(`注册消息${this.settings}`)
    for (let index in this.settings) {
      this.client.subscribe(this.settings[index], frame => this.onmessage(frame));
    }
  }

  /* 发送 */
  send(destination, headers, body) {
    if (this.client.connected) {
      this.client.send(destination, headers, body);
    }
  }

  /* 发生错误 */
  onerror() {
    // console.log(`websocket [${this.url}] 连接出现错误：\n${error.message}`);
    // TODO 断线重连还有问题
    setTimeout(this.connect(), 5000);
  }

}