<?php

//        # Copyright (C) 2012-2013 GNU remotecontrol authors.
//        #
//        # This program is free software: you can redistribute it and/or modify
//        # it under the terms of the GNU Affero General Public License as
//        # published by the Free Software Foundation, either version 3 of the
//        # License, or (at your option) any later version.
//        #
//        # This program is distributed in the hope that it will be useful,
//        # but WITHOUT ANY WARRANTY; without even the implied warranty of
//        # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//        # GNU Affero General Public License for more details.
//        #
//        # You should have received a copy of the GNU Affero General Public License
//        # along with this program.  If not, see <http://www.gnu.org/licenses/>.

	class IPThermostat
	{
		// Properties
		public $ID;
		public $DeviceName;
		public $SiteName;
		public $ModelNumber;
		public $LowTempAlarm;
		public $HighTempAlarm;
		public $FilterReminder;
		public $HighHumidityAlarm;
		public $JUTName;
		public $Description;
		public $Host;
		public $Port;
		public $ObjectArray;
                public $ObjectsToUpdate;
		public $AuthString;
                public $TimeZoneOffset;
                public $Selected;

		// Constructor
		public function  __construct()
		{
			$numargs = func_num_args();
			$args = func_get_args();
			
			switch($numargs)
			{
				case 2:
					
					$this->ID = $args[0];
					$this->DeviceName = '';
					$this->SiteName = '';
					$this->ModelNumber = '';
					$this->LowTempAlarm = '';
					$this->HighTempAlarm = '';
					$this->FilterReminder = '';
					$this->HighHumidityAlarm = '';
					$this->JUTName = '';
					$this->Description = '';
					$this->Host = '';
					$this->Port = '';
					$this->ObjectArray = new IPThermostatObjectCollection(true);
					$this->AuthString = '';
                                        $this->TimeZoneOffset = new TimeZoneOffset();
					$this->Selected = false;

					if($args[1] === true)
					{
						$this->Load();
					}
					
					break;
				
				case 6:
					
					$this->ID = $args[0];
					$this->DeviceName = '';
					$this->SiteName = '';
					$this->ModelNumber = '';
					$this->LowTempAlarm = '';
					$this->HighTempAlarm = '';
					$this->FilterReminder = '';
					$this->HighHumidityAlarm = '';
					$this->JUTName = $args[1];
					$this->Description = $args[2];
					$this->Host = $args[3];
					$this->Port = $args[4];
					$this->ObjectArray = new IPThermostatObjectCollection(true);
					$this->AuthString = $args[5];
                                        $this->TimeZoneOffset = new TimeZoneOffset();
					$this->Selected = false;

					if($this->AuthString)
					{
						$this->LoadCurrentObjectValues();
					}
					
					break;
                                        
                                case 7:
					
					$this->ID = $args[0];
					$this->DeviceName = '';
					$this->SiteName = '';
					$this->ModelNumber = '';
					$this->LowTempAlarm = '';
					$this->HighTempAlarm = '';
					$this->FilterReminder = '';
					$this->HighHumidityAlarm = '';
					$this->JUTName = $args[1];
					$this->Description = $args[2];
					$this->Host = $args[3];
					$this->Port = $args[4];
					$this->ObjectArray = new IPThermostatObjectCollection(true);
					$this->AuthString = $args[5];
                                        $this->TimeZoneOffset = $args[6];
					$this->Selected = false;

					if($this->AuthString)
					{
						$this->LoadCurrentObjectValues();
					}
					
					break;
				
				default:
					
					$this->ID = -1;
					$this->DeviceName = '';
					$this->SiteName = '';
					$this->ModelNumber = '';
					$this->LowTempAlarm = '';
					$this->HighTempAlarm = '';
					$this->FilterReminder = '';
					$this->HighHumidityAlarm = '';
					$this->JUTName = '';
					$this->Description = '';
					$this->Host = '';
					$this->Port = '';
					$this->ObjectArray = new IPThermostatObjectCollection(true);
					$this->AuthString = '';
                                        $this->TimeZoneOffset = new TimeZoneOffset();
					$this->Selected = false;
					
					break;
			}
		}

		// Methods
		public function Execute()
		{
			$ch = curl_init("http://$this->Host:$this->Port/pdp");

			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_TIMEOUT, 10);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
			curl_setopt($ch, CURLOPT_USERPWD, $this->AuthString);
			
			$params = '';

			foreach($this->ObjectsToUpdate as $obj)
			{
				if($obj->NewValue != $obj->CurrentValue)
				{
					$params .= "$obj->OID=$obj->NewValue&";
				}
			}

			$response = '';

			if($params)
			{
				$params .= 'submit=Submit';

				curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

				$response = curl_exec($ch);
			}
			else
			{
				$response = 'NT';
			}

			if($response === false)
			{
				$errorlog = new ErrorLog(curl_error($ch));
				$errorlog->Save();
			}			

			curl_close($ch);

			return $response;
		}

		public function Load()
		{
			$dataAccess = new MySqlDataAccess(Common::ConnectionString);
			$dataAccess->Command->CommandType = CommandType::StoredProcedure;
			$dataAccess->Command->CommandText = "CALL sp_Thermostat_Load_Details($this->ID)";
			$dataAccess->GetData();

			$row = $dataAccess->ResultSet->fetch_assoc();

			$this->JUTName = $row['Name'];
			$this->Description = $row['Description'];
			$this->Host = $row['Host'];
			$this->Port = $row['Port'];                                                
                        $this->TimeZoneOffset = new TimeZoneOffset($row['TimeZoneOffsetID'], true);
			$this->AuthString = $row['AuthString'];

			$dataAccess->Cleanup();

			if($this->AuthString)
			{
				$this->LoadCurrentObjectValues();
			}
		}

		private function LoadCurrentObjectValues()
		{
			//$this->Ping();
			if($this->Ping() !== false)
			{                            
				$ch = curl_init("http://$this->Host:$this->Port/get");

				curl_setopt($ch, CURLOPT_POST, true);
				curl_setopt($ch, CURLOPT_TIMEOUT, 10);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
				curl_setopt($ch, CURLOPT_USERPWD, $this->AuthString);

				$params = '';

				$counter = 1;

				foreach($this->ObjectArray as $obj)
				{
					if($counter == $this->ObjectArray->count())
					{
						$params .= "$obj->OID=";
					}
					else
					{
						$params .= "$obj->OID=&";
					}

					$counter++;
				}

				curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

				$response = curl_exec($ch);

				if($response === false)
				{
					$errorlog = new ErrorLog(curl_error($ch));
					$errorlog->Save();
				}

				curl_close($ch);

	//			$file = fopen(dirname(__FILE__).'\..\\'.'\response.txt', 'a');
	//
	//			fwrite($file, $response.'####');
	//
	//			fclose($file);

				$oids = array();

				parse_str($response, $oids);

				foreach($oids as $oid => $value)
				{
					switch($oid)
					{
						case 'OID1_2':

							$this->DeviceName = $value;

							break;

						case 'OID1_10_9':

							$this->SiteName = $value;

							break;

						case 'OID1_13_2_1':

							$this->LowTempAlarm = $value;

							break;

						case 'OID1_13_2_2':

							$this->HighTempAlarm = $value;

							break;

						case 'OID1_13_2_3':

							$this->FilterReminder = $value;

							break;

						case 'OID1_13_2_4':

							$this->HighHumidityAlarm = $value;

							break;

						case 'OID2_7_1':

							$this->ModelNumber = $value;

							break;

						case 'OID2_5_1':

							$this->ObjectArray->FindObjectByOID(str_replace('_', '.', $oid))->CurrentValue = $value;
							$this->ObjectArray->FindObjectByOID(str_replace('_', '.', $oid))->NewValue = $value;

							break;

						default:

							$this->ObjectArray->FindObjectByOID(str_replace('_', '.', $oid))->CurrentValue = $value;

							break;
					}
				}
			}
		}

		public function Ping()
		{                    
                    $ch = curl_init("http://$this->Host:$this->Port/");

                    curl_setopt($ch, CURLOPT_NOBODY, true);
                    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
                    
                    $resp = curl_exec($ch);
                    
                    curl_close($ch);

                    return $resp;
		}

		public function Save()
		{
			
		}
	}

?>
