'use strict';
var calendar = require('./calendarInterface');
var mqttClient = require('../mqtt/mqttClient');
var cron = require('node-cron');
var log4js = require('log4js');
var logger = log4js.getLogger();
var events = require('events');
var eventBus ;
var util = require('util');

var officeController = function(neweventbus) {

  logger.debug((typeof neweventbus));
  if ((typeof neweventbus !== 'undefined') && (neweventbus !== null)) {
    logger.warn('Using passed eventBus');
    eventBus = neweventbus;
  } else {
    logger.warn('Using internal eventBus');
    eventBus = new events();
  }

  console.log('~~~ officeController');
  this.cloneObject = function(from, to) {
      if (Object.keys(from).length !== 0) {
        for (var key in from) {
          if (from.hasOwnProperty(key)) {
            if (key !== 'cronJOBS') {
              to[key] = from[key];
            }
          }
        }
      }
    };

  var self = this;
  this.schedule = {};
  this.todaysList = {};

  this.calendarControl = new calendar.calendarInterface();
  this.calendarControl.getRoomStatusV2((todaysList) => {

      this.todaysList = todaysList;
      /*This.todaysList = {};
      this.cloneObject(todaysList, this.todaysList);
  logger.debug(this.todaysList);*/
      this.setupNextMeeting(todaysList);
    });
  this.mqtt = new mqttClient.mqttClient();

  //This.timer;

  //  this.meetings = {cronjobs:{start:null.stop:null}};
  this.task = cron.schedule('* * * * *', function() {
      var n = new Date();
      logger.debug('tick: ' + n);
      logger.info('looped Schedule count: ' + Object.keys(this.schedule).length);

      var curMeeting = {};
      this.cloneObject(this.todaysList.current, curMeeting);
      curMeeting.cronJobs = {};

      eventBus.emit('sendSocket', {id:'calendar',current:curMeeting});
    }.bind(this));

  this.task = cron.schedule('*/5 * * * *', function() {
      this.calendarControl.getRoomStatusV2((todaysList) => {
          this.todaysList = todaysList;
          this.setupNextMeeting(todaysList);
          var data = todaysList;
          data.id = 'calendarData';
          eventBus.emit('sendSocket', data);
        });
    }.bind(this));

  eventBus.on('setupNextMeeting', this.setupNextMeeting.bind(this, this.todaysList));

  eventBus.on('cleanUp', (id) => {
      logger.debug('+ => cleanUp');
      this.cleanUpMeeting(id);
    });
};

officeController.prototype.cleanUpMeeting = function(id) {
    logger.debug('deleting scheduled item: ' + id);
    logger.info('Pre delete Schedule count: ' + Object.keys(this.schedule).length);
    delete this.schedule[id];
    logger.info('post delete Schedule count: ' + Object.keys(this.schedule).length);

  };

officeController.prototype.createMeeting = function(obj,delayStart) {
  // Logger.debug(util.inspect(this));

  var newMeeting = obj, _delayStart = delayStart || false, cronStartStr;
  var now = new Date.create();
  var self = this;
  //  Logger.debug(newMeeting);
  newMeeting.cronJOBS = {start: null, stop: null};
  if (_delayStart) {
    cronStartStr = now.addSeconds(15).format('{s} {m} {H} * * *');
  } else {
    cronStartStr = newMeeting.cronStart;
  }


  newMeeting.cronJOBS.start = cron.schedule(cronStartStr, function() {
      var n = new Date();
      logger.debug('MEETING STARTED!!!!' , n);
      var key = Object.keys(self.schedule)[0];
      var curMeeting = {};
      self.cloneObject(self.schedule[key], curMeeting);
      curMeeting.cronJOBS = null;

    eventBus.emit('sendSocket', {id:'calendar',current:curMeeting});


    }, true);

  newMeeting.cronJOBS.stop = cron.schedule(newMeeting.cronStop, function() {
      var n = new Date();
      logger.debug('MEETING ENDED' + n);
      newMeeting.cronJOBS.start = null;
      newMeeting.cronJOBS.stop = null;

      logger.debug(newMeeting.cronJOBS);
      eventBus.emit('cleanUp',newMeeting.uid);

    }.bind(this), true);

  this.schedule[newMeeting.uid] = newMeeting;

};

officeController.prototype.setupNextMeeting = function(calData) {
    logger.debug('Setup next meeting...');

    var self = this;

    var now = new Date.create();
    if (Object.keys(calData.current).length > 0) {

      if (this.schedule.hasOwnProperty(calData.current.uid)) {
        logger.debug('Current Meeting exists in schedule');
      } else {
        logger.debug('Current Meeting does NOT exist in schedule');
        this.createMeeting(calData.current, true);
      }
    }

    if (calData.upcoming.length > 0) {

      for (var uCount = 0; uCount < calData.upcoming.length; uCount++) {
        var uEntry = calData.upcoming[uCount];
        if (this.schedule.hasOwnProperty(uEntry.uid)) {

          logger.debug('Upcoming Meeting exists in schedule');
          // Lets check to see if it's changed in anyway..

          var origEntry, origStart, origEnd, newStart, newEnd;

          origEntry = this.schedule[uEntry.uid];
          origStart = Date.create(origEntry.dtstart);
          origEnd = Date.create(origEntry.dtend);

          newStart = Date.create(uEntry.dtstart);
          newEnd = Date.create(uEntry.dtend);

          if ((origStart.getTime() != newStart.getTime()) || (origEnd.getTime() != newEnd.getTime())) {
            logger.error('WE HAVE A CHANGED ENTRY!!');

            origEntry.cronJOBS.start.destroy();
            origEntry.cronJOBS.stop.destroy();

            origEntry = uEntry;
            this.createMeeting(origEntry);
          }

        } else {
          logger.debug('Upcoming meeting does NOT exist in schedule');
          var newMeeting = uEntry;
          this.createMeeting(newMeeting);
        }

      }

    }

    //  Logger.info(this.schedule);
  };


officeController.prototype.startController = function(eventBus) {
    console.log('Starting.');
    getRoomStatus();
    this.timer = setInterval(function() { getRoomStatus() }, 300000);
  };

officeController.prototype.stopController = function() {
    console.log('Stopping.');
    clearInterval(this.timer);
  };

officeController.prototype.returnCalendar = function() {
  var exportList;

  exportList = this.calendarControl.getCachedStatus();
  logger.debug(exportList);
  return exportList;

};

//OfficeController.prototype.getRoomStatus = function () {
//    this.calendarControl.getRoomStatus();
//    console.log('Checking Calendar.');
//};

var meetingStates = {
    STARTING: 0,
    INPROGRESS: 1,
    NONE: 2,
    FINISHED: 3
  };

function getRoomStatus() {
  return;
  // Var calendarControl = new calendar.calendarInterface();
  //  var status = calendarControl.getRoomStatusV2();
  var status = officeController.calendarControl.getRoomStatusV2();
  if (status == meetingStates.STARTING) {
    console.log('Meeting about to start - turning on.');
    this.mqtt.projectorOn();
    this.mqtt.lightsOn();
  }
  if (status == meetingStates.INPROGRESS) {
    console.log('Meeting in progress - do nothing.');
  }
  if (status == meetingStates.NONE) {
    console.log('No meeting - do nothing.');
  }
  if (status == meetingStates.FINISHED) {
    console.log('No meeting - do nothing.');
    this.mqtt.projectorOff();
    this.mqtt.lightsOff();
  }


}



module.exports.officeController = officeController;