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

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

function setOutValveTo(controller_id, nextState) {
  var state = controller_state(controller_id);
  ControllerState.update(state._id, {
    '$set': {
      'state.out_valve': nextState,
      'time': new Date(),
      'set_by': 'server'
    }
  });
}

function openOutValve(controller_id) {
  setOutValveTo(controller_id, 'opening');
  var state = controller_state(controller_id);
  var config = state.config;
  var jobName = "Close out valve " + state.controller_id + " after draining";
  console.log("Opening valve ", controller_id, jobName);
  SyncedCron.remove(jobName);
  SyncedCron.add({
    name: jobName,
    schedule: function(parser) {
      var time = moment().add(config.draining_period_amount, config.draining_period_unit).toDate();
      return parser.recur().on(time).fullDate();
    },
    job: function() {
      closeOutValve(controller_id);
    }
  });
  console.log(Meteor.sharedFunctions);

  Meteor.sharedFunctions.reactToSensorData(last_sensor_reading(controller_id));
}

function closeOutValve(controller_id) {
  var state = controller_state(controller_id);

  var jobName = "Close out valve " + state.controller_id + " after draining";
  console.log("Closing valve ", controller_id, jobName);
  SyncedCron.remove(jobName);
  setOutValveTo(controller_id, 'closing');
  console.log("Finished clearing cron ", controller_id);

  console.log(Meteor.sharedFunctions);

  Meteor.sharedFunctions.reactToSensorData(last_sensor_reading(controller_id));
}

function clearLog() {
  console.log("Removing sensor data");
  SensorData.remove({});
}

function saveControllerConfig(controller_id, time, days) {
  var state = controller_state(controller_id);
  ControllerState.update(state._id, {
    '$set': {
      'config.automaticTimeOfDay': time,
      'config.automaticDaysOfWeek': days
    }
  });
  var jobName = "automatic_" + controller_id;
  var times = time.split(":");
  var hours = parseInt(times[0]);
  var minutes = parseInt(times[1]);

  SyncedCron.remove(jobName);
  SyncedCron.add({
    name: jobName,
    schedule: function(parser) {

      var period = parser.recur();
      for (var i = 0; i < days.length; i++) {
        period = period.and().on(parseInt(days[i])).dayOfWeek().on(hours).hour().on(minutes).minute();
      }
      return period;
    },
    job: function() {
      openOutValve(controller_id);
    }
  });
}


function last_sensor_reading(controller_id) {
  var result = null;

  if (controller_id) {
    result = SensorData.find({
      controllerId: controller_id
    }, {
      sort: {
        created_at: -1
      },
      limit: 1
    });
  }
  if (result && result.count() > 0) {
    return result.fetch()[0];
  } else {
    return {}
  }
}


Meteor.methods({
  openOutValve: openOutValve,
  closeOutValve: closeOutValve,
  clearLog: clearLog,
  saveControllerConfig: saveControllerConfig
});
