import {WEBSOCKET_HOST} from '@/utils/config'

const webSocketService = {
  webSocket: null,
  init: function(){
    this.webSocket = new WebSocket(WEBSOCKET_HOST);
  },
  onOpen: function(that, callback){
    if(this.webSocket === null){
      this.init();
    }
    this.webSocket.onopen = function(evt){
      if(typeof callback === 'function'){
        callback(evt);
      }
    };
  },
  onMessage: function(that, callback){
    if(this.webSocket === null){
      this.init();
    }
    this.webSocket.onmessage = function(res){
      if(typeof callback === 'function'){
        callback(res);
      }
    }
  },
  onClose: function(that, callback){
    if(this.webSocket === null){
      this.init();
    }
    this.webSocket.onclose = function(evt){
      if(typeof callback === 'function'){
        callback(evt);
      }
    };
  },
  onSend: function (that, data) {
    if(this.webSocket === null){
      this.init();
    }
    this.webSocket.send(data);
  }
};
webSocketService.init();
export default webSocketService;