const WEBSOCKET = function (model) {

  const useUrl = 0;
  let wsUrl = ['localhost', 'silvrtree.co.uk'];
  const wsPort = '3010';
console.log(document.location);
  if ('https:' === document.location.protocol) {
  //  wsUrl = 'wss://' + wsUrl[useUrl] + '';
    wsUrl = 'wss://' + document.location.host ;
    // wsPort = '';
  } else {
    //wsUrl = 'ws://localhost:3001';
  //  wsUrl = 'ws://' + wsUrl[useUrl] + '';
    //  wsPort = '';
    wsUrl = 'ws://' +  document.location.host ;
  }


  this.socket = null;
  this.timer = 0;
  this.clock = null;

  this.startWebSocket = function () {
    'use strict';

   // const url = (wsPort === '') ? wsUrl : wsUrl + ':' + wsPort;
    const url =  wsUrl;
    console.log('Starting socket', url);
    const wsCtor = window['MozWebSocket'] ? MozWebSocket : WebSocket;
    this.socket = new wsCtor(url, 'stream');

    this.socket.onopen = this.handleWebsocketOnOpen.bind(this);
    this.socket.onmessage = this.handleWebsocketMessage.bind(this);
    this.socket.onclose = this.handleWebsocketClose.bind(this);
    this.socket.onerror = function (e) {
      console.error(e);
    };

  };

  this.send = function (msg) {
    console.log('Sending', msg);
    this.socket.send(msg);
  };


  this.handleData = function (d) {
    model.trigger('message', d);
  };

  this.handleWebsocketOnOpen = function () {
    'use strict';
    this.retry = 0;

    console.log('**** Websocket Connected ****');
    this.clock = new Date();
  };

  this.handleWebsocketMessage = function (message) {
    let command;

    try {
      command = JSON.parse(message.data);
    }
    catch (e) { /* Do nothing */
    }
    if (command) {
      this.handleData.call(this, command);
    }
  };

  this.handleWebsocketClose = function () {
    console.error('WebSocket Connection Closed.');
    const now = new Date();

    const uptime = now.getTime() - this.clock.getTime();
    console.log('Socket alive for', uptime / 1000);
    const self = this;
    console.log('Waiting ', 5000);
    this.timer = setTimeout(function () {
      self.startWebSocket();
    }, 5000);
  };

  this.startWebSocket();

};