/**
 *
 * User: Martin Donnelly
 * Date: 2016-09-09
 * Time: 11:38
 *
 */
/* global Backbone, _,  WEBSOCKET */
/* jshint browser: true , devel: true*/

'use strict';

var SOCKETMANAGER = (function() {

  var SocketManager = Backbone.Model.extend({
    deviceId: ['CENSIS-LoRa-1','CENSIS-LoRa-2','CENSIS-LoRa-3','CENSIS-LoRa-4','HIE-mobile-1----','HIE-mobile-2----','HIE-smart-campus-1','HIE-smart-campus-2','HIE-smart-campus-3','HIE-smart-campus-4','HIE-smart-campus-5','HIE-smart-campus-6','HIE-smart-campus-7','HIE-mDot-1'],

    initialize: function() {
          _.bindAll(this, 'turnOn', 'turnOff');
          this.listeningID = null;
          this.listening = false;
          this.webSocket = new WEBSOCKET(this);

          this.on('message', function(o) {
            if (this.listening) {
              this.checkItem(o);
            }

          });
        },
    turnOn: function() {
          this.listening = true;
        },
    turnOff: function() {
          this.listening = false;
        },
    listenFor: function(id) {
          this.listeningID = this.deviceId.indexOf(id);
        },
    checkItem: function(item) {
        if (item.hasOwnProperty('tick')) {
          // Ticks are ignored
        } else {
          if (item.data.deviceid === this.listeningID) {
            console.log('Updated', item.data);
            this.set({data: item.data});
          }
        }

      }
  });

  return SocketManager;
}());


