controller_state = function() {
  var controller = Session.get('controller_id');
  var result = {}
  if (controller) {
    result = ControllerState.findOne({
      controller_id: controller
    });
  }

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

config = function() {
  return Meteor.zoblak.client.controller_state().config;
}


Template.alarm_settings.helpers({
  config: function(property) {

    console.log('asking for property', property);
    console.log('config is', config());
    var result = config()[property];
    console.log('returning', result);
    return result;
  },

  pretty_temperature: function(temperature) {
    var temperatureLabel = (Meteor.zoblak.shared.valid_temperature(temperature)) ? temperature : "XX.X";
    return '' + temperatureLabel + ' °C ';
  },

  sensors: function() {
    var temperatures = Meteor.zoblak.client.last_sensor_reading().temperatures;
    var enabled = config()['sensorsEnabled'] || {};
    var sensors = [];
    for (var index in temperatures) {
      var is_on = (index in enabled) ? enabled[index] : true; // on by default
      var value = parseFloat(temperatures[index])
      sensors.push({
        value: value,
        on: is_on
      })
    }
    return sensors;
  }
});

Template.alarm_settings.events({
  'click #save_settings': function() {
    var controller_id = Meteor.zoblak.client.controller_state().controller_id;
    1
    var instance = Template.instance();
    var minTemperature = instance.$('#min_temperature').val();
    var maxTemperature = instance.$('#max_temperature').val();
    var timeoutBox = instance.$('#timeout_box').val();
    var timeoutPhone = instance.$('#timeout_phone').val();
    var sms1 = instance.$('#sms1').val();
    var sms2 = instance.$('#sms2').val();
    var sms3 = instance.$('#sms3').val();
    var sms4 = instance.$('#sms4').val();

    var sensorSwitches = instance.$('.sensor_switch');
    var enabled = {};

    sensorSwitches.each( function(index,element) {
      enabled[index] = instance.$(element).is(':checked');
    } );

    console.log("Enabled: ", enabled);

    Meteor.call('saveAlarmSettings', controller_id, minTemperature, maxTemperature, timeoutBox, timeoutPhone, [sms1, sms2, sms3, sms4] ,enabled);
  }
});
