SensorData = new Mongo.Collection("sensorData");
ControllerState = new Mongo.Collection("controller_states");
Picture = new Mongo.Collection("pictures");


Meteor.zoblak = {}
Meteor.zoblak.client = {
  controller_state: function() {
    result = ControllerState.findOne({});
    if (!result) {
      result = {}
    };
    return result;
  },

  config: function() {
    Meteor.zoblak.client.controller_state().config
  },

  accessible: function(feature) {
    var controller = Meteor.zoblak.client.controller_state();

    console.log('cotnroller ', controller);
    if (!controller.features) return false;

    return controller.features[feature] === true;
  },

  sensor_data_collection: function() {
    var controllerId = Session.get('controller_id');
    return SensorData.find({
      controllerId: controllerId
    }, {
      sort: {
        created_at: -1
      },
      limit: 3
    });
  },

  last_sensor_reading: function() {
    var controller = Session.get('controller_id');
    var result = null;
    if (controller) {
      result = Meteor.zoblak.client.sensor_data_collection();
    }
    if (result && result.count() > 0) {
      return result.fetch()[0];
    } else {
      return {}
    }
  }
}

Meteor.zoblak.shared = {
  valid_temperature: function(value) {
    return (parseFloat(value) > -40 && parseFloat(value) < 50);
  }
}

Meteor.zoblak.server = {
  controller_state: function(controller_id) {
    var result = {}
    if (controller_id) {
      result = ControllerState.findOne({
        controller_id: controller_id
      });
    }

    if (!result) {
      result = {}
    };
    return result;
  },

  on_all_controllers: function(whatToDo) {
    var ids = ControllerState.find({}, {
      fields: {
        'controller_id': 1
      }
    }).map(function(cid) {
      return cid.controller_id
    });

    for (var index in ids) {
      var controller_id = ids[index];
      try {
        whatToDo(controller_id);
      } catch (err) {
        console.log('Cannot call ', whatToDo, controller_id, err);
      }
    }
  }
}
