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

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

Template.alarm.helpers({
  last_reading: last_sensor_reading,
  state: function() {
    return Meteor.zoblak.client.controller_state().state;
  },
  pretty_time: function(time) {
    return moment(time).format("DD.MM.YYYY, HH:mm")
  },
  all_temperatures: function() {
    var result = "";
    var temperatures = last_sensor_reading().temperatures;

    for (var i in temperatures) {
      result += '' + parseFloat(temperatures[i]).toFixed(1) + ' °C ';
    }
    return result;
  }
});

Template.alarm.events({
  'click #run_alarm_settings': function() {
    Modal.show('alarm_settings');
  },
  'click #stop_alarm': function() {
    let controller_id = Meteor.zoblak.client.controller_state().controller_id;
    Meteor.call('stopTheAlarm', controller_id);
  }
});

Template.alarm.helpers({

});
