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

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

Template.settings.helpers({
  timeSelected: function(time) {
    var config = controller_state().config;
    return config.automaticTimeOfDay == time;
  },

  dayChecked: function(day) {
    var config = controller_state().config;
    var days = config.automaticDaysOfWeek || [];
    return days.includes(day)
  },


});

Template.settings.events({
  'click #save_settings': function() {
    var instance = Template.instance();
    selectedTime = instance.$('#time_of_day').val();
    selectedDays = [];
    instance.$('.day_checkbox').each(function() {
      if (this.checked) {
        selectedDays.push(instance.$(this).val());
      }
    });
    var controller_id = Session.get('controller_id');
    Meteor.call('saveControllerConfig', controller_id, selectedTime, selectedDays);
  }
});

Template.sensorData.helpers({
  created_at_formatted: function() {
    return moment(this.created_at).format("DD.MM.YYYY, HH:mm")
  }
});
