/*
Set timers in the AM to wake device and keep Digital Signage running
Timers in the PM allow device to go into standby but wake when 
someone enters the room but digital signage only plays for short amount of time once in halwake state
*/
import xapi from 'xapi';

const Sunday = 0, Saturday = 6;


const ScheduleTimeAM = '07:00';  // Set this to the time you want to have the device do something
const ScheduleTimePM = '17:00';

const ScheduleTime = [ScheduleTimeAM, ScheduleTimePM]


function schedule(time, firstRun) {
  
    let [alarmH, alarmM] = time.split(':');
    let now = new Date();
    let hour = now.getHours();
    now = now.getHours() * 3600 + now.getMinutes() * 60 + now.getSeconds();
    console.log("Time now:" + now);
    let difference = parseInt(alarmH) * 3600 + parseInt(alarmM) * 60 - now;
    if (difference <= 0) difference += 24 * 3600;
    
    if(time==ScheduleTimeAM){
        if(parseInt(alarmH) < hour && parseInt(ScheduleTimePM.split(':')[0]) > hour && firstRun === "true" ){
            setTimersAM("true")
        }
        console.log("Setting Timeout for later" + difference * 1000);
        return setTimeout(setTimersAM, difference * 1000)
    }else{
        console.log(parseInt(alarmH) < hour && parseInt(ScheduleTimeAM.split(':')[0]) > hour && firstRun === "true")
        if(parseInt(alarmH) < hour && parseInt(ScheduleTimeAM.split(':')[0]) > hour && firstRun === "true"){
            setTimersPM("true")
        }
        return setTimeout(setTimersPM, difference * 1000)
    }
}

function setTimersAM(skipSchedule) {
    const weekDay = new Date().getDay();
    if (weekDay !== Sunday && weekDay !== Saturday) {
        console.log("setting new AM settings");
        xapi.Config.Standby.WakeupOnMotionDetection.set("Off");
        xapi.Config.Standby.Delay.set("400");
        xapi.command('Standby Deactivate');
    }
    if(skipSchedule === "true"){
      return
    }else{
      schedule(ScheduleTimeAM);
    }
}
function setTimersPM(skipSchedule) {
    const weekDay = new Date().getDay();
    if (weekDay !== Sunday && weekDay !== Saturday) {
      console.log("setting new PM settings");
      xapi.Config.Standby.WakeupOnMotionDetection.set("On");
      xapi.Config.Standby.Delay.set("2");

    }
    if(skipSchedule === "true"){
      return
    }else{
      schedule(ScheduleTimePM);
    }
    
}


for (let i = 0; i < ScheduleTime.length; i++) {
  console.log(ScheduleTime[i])
  schedule(ScheduleTime[i], "true");
}