<?php
ini_set("display_errors",1);
error_reporting(E_ALL);
date_default_timezone_set("UTC"); 
require_once 'lib/swift_required.php';
set_time_limit(0); //The program can be ended manually by  resetting the frequency text file or an abnormal fault on the computer.
$fname="debugger.txt";
$nfile = fopen($fname, "w");
if($nfile != false) { 
	fwrite($nfile,"1");
	fclose($nfile);
};


$f=$argv[1];
$inputs=explode(",",$f);
$username = $inputs[0];
$password = $inputs[1];
$frequency = $inputs[2];
$initial = $inputs[3];
$email1= $inputs[4];
$email2= $inputs[5];
$email3= $inputs[6];
$email4= $inputs[7];
$smtp= $inputs[8];
$port= $inputs[9];
/*
$username = 'percival.connect@';
$password = '';
$frequency = 1;
$initial = 21;
$email1= '';
$email2= '';
$email3= '';
$email4= '';
*/

//Hours to send a status e-mail.
$frequencyCheck=0;
//Set up e-mail credentials.
$transport = Swift_SmtpTransport::newInstance($smtp,$port)//removed tls
  ->setUsername("{$username}")
  ->setPassword("{$password}");
//Initialize a few variables
$frequency2= $frequency;
$messageSent=0;
$time=time()-0;
$currentHour = (int)(($time-$time%300)/300)%288;
$frequencyCheck=12*((($initial-$currentHour)%$frequency<0)?($initial-$currentHour)%$frequency+$frequency:($initial-$currentHour)%$frequency);
$currentHour = (int)(($time-$time%300)/300)%288;
$fname="debugger.txt";
$e=0;
$nfile = fopen($fname, "w");
if($nfile != false) { 
	fwrite($nfile,"2");
	fclose($nfile);
};
//Start the mailer loop.
while(($frequency==$frequency2)) {
	$time=time()-0;
	$debugHour=(int)(($time-$time%300)/300)%288;
	//Repeat file and alarm checks at least once a minute.
	sleep(60); 
	 //Get current hour to see whether a regular status e-mail needs to be sent.
	if($currentHour==(int)(($time-$time%300)/300)%288 ) {
	} else {
		if((($activeAlarm==1)&&($frequencyCheck>12))||($activeAlarm==0)) { //If an alarm is detected, will only send out once per hour.
			$messageSent = 0;
		};
		$currentHour = (int)(($time-$time%300)/300)%288;
		$frequencyCheck++;
	};
	//Check for whether the stop e-mail function was ran.
	$filename = "frequency.txt";
	$handle = fopen($filename, "rb");
	$frequency2= fread($handle, filesize($filename));
	fclose($handle);
	//Grab stuff from the Mongo database.
	$m = new MongoClient("mongodb://127.0.0.1:27017");
	$coll=$m->selectCollection("intelluscloud","chamber");
	$cursor=$coll->find();
	$activeAlarm=0;
	$string="Chamber status update.\n";
	foreach ($cursor as $doc) {
        if(isset($doc["Name"])) {
		$currentStatus=$doc["CurrentStatus"];
		$dataValues=$currentStatus["DataValues"];
		$setPoints=$currentStatus["SetPoints"];
		$currentName=$doc["Name"];
		$lightStatus=$currentStatus["LightStatus"];
		$alarmStatus=$currentStatus["AlarmStatus"];
        //DMI - Change to not only avoid processing out of date chambers, but a small catch to try to take into account differing mongo versions.
        if(is_object($currentStatus["Timestamp"])) {
            $timestamp=$currentStatus["Timestamp"]->sec;
        } elseif(isset($currentStatus["Timestamp"]["\$date"])) {
            $timestamp=$currentStatus["Timestamp"]["\$date"]/1000;
        } else {
            //Avoid doing the check at all.
            $timestamp=strtotime('-2 months');
            //$timestamp=$currentStatus["Timestamp"];
        };
        if($timestamp>strtotime('-3 months')) { //This line too
            if((!isset($dataValues[2][1]))&&(!isset($dataValues[1][1]))) {
                $string.="\n{$currentName} Status\nTemp PV/SP: {$dataValues[0][1]}C/{$setPoints[0][1]}C\n";
            } elseif(!isset($dataValues[2][1])) {
                $string.="\n{$currentName} Status\nTemp PV/SP: {$dataValues[0][1]}C/{$setPoints[0][1]}C\nRH PV/SP: {$dataValues[1][1]}%/{$setPoints[1][1]}%\n";
            } else {
                $string.="\n{$currentName} Status\nTemp PV/SP: {$dataValues[0][1]}C/{$setPoints[0][1]}C\nRH PV/SP: {$dataValues[1][1]}%/{$setPoints[1][1]}%\nCO2/LS1 PV/SP: {$dataValues[2][1]} PPM/UML/{$setPoints[2][1]}PPM/UML\n";
            };
            if($lightStatus==1) {
                $string.="Lights are on.\n";
            } else {
                $string.="All lights are off.\n";
            };
            if($alarmStatus) {
                $string.="AN ALARM IS ACTIVE ON THIS CHAMBER.\n\n";
                $activeAlarm=1;
            };
        };
        };
	};
	//Send an e-mail either if it's a time to update it, or if there is a new alarm set off.
	if((($frequencyCheck>=$frequency)&&($messageSent==0))||(($activeAlarm==1)&&($messageSent==0))) {
		try{
			$mailer = Swift_Mailer::newInstance($transport);
			$mailingList=array_filter(array($email1,$email2,$email3,$email4));
            if($alarmStatus==0) {
                $title='ISSES';                                    //Changed joe to ISSES from INTELLUS STATUS UPDATE
            } else {
                $title='ISSES:  ALARM';// changed joe 
            };
			$message = Swift_Message::newInstance($title)
			  ->setFrom(array('ISSES@controller.com' => 'ISSES'))//changed from INTELLUS STATUS UPDATE to ISSES-joe
			  ->setTo($mailingList)
			  ->setBody($string);
			$result = $mailer->send($message);
			$mailer->getTransport()->stop();
			$messageSent=1;
			//Don't reset everything because of the alarm.
            if($activeAlarm==1) {
                if($frequencyCheck>=$frequency) {
                    $frequencyCheck=0;
                };
            } else {
                $frequencyCheck=0;
            };
		} catch(Exception $e) {
			echo 'Caught exception', $e->getMessage(), "\n";
			//Setting this to 0 will ensure we will return to this and trying emailing again in a minute.
			$currentHour=($currentHour-1);
			$messageSent=0;
			$frequencyCheck=$frequency+1;
		};
		$fname="debugger.txt";
		$nfile = fopen($fname, "w");
		if($nfile != false) { 
			fwrite($nfile,"inside check,{$currentHour},{$debugHour},{$messageSent},{$frequencyCheck},{$activeAlarm},{$frequency},{$e}");
			fclose($nfile);
		};
	};
};

$fname="debugger.txt";
$nfile = fopen($fname, "w");
if($nfile != false) { 
	fwrite($nfile,"4,{$frequency},{$frequency2}");
	fclose($nfile);
};
?>
