<?php

require_once('URCSystemData.php');

class CloudController extends BaseController {

	public function doSearch($deviceType) {

		if(!$this->chkJWTTokenWithLevel(URCValues::LOGIN_USER, $errMsg, $errNo)) {
			return Response::make($errMsg, $errNo);
		}
		
		$deviceType = strtoupper($deviceType);

		if(URCValues::isBasestation($deviceType) || URCValues::isRemoteControl($deviceType)
			|| $deviceType == 'SNP-2') {

			$systemId = Input::get('systemId');
			$controllerId = URCSystemData::getControllerId($this->usr_id/*//JWT->Auth::id()*/, $systemId);
			if($controllerId === false) {
				return Response::json(array('result' => false, 'error' => 'not valid'));
			}

			$sip_user = DB::table('sip_user')->where('controller_id', '=', $controllerId)->first();
			if(!$sip_user) {
				return Response::json(array('result' => false, 'error' => 'Not valid communication account'));
			}

			$deviceMac = 'ffffffffffff';
			if(Input::has('mac')) {
				$deviceMac = Input::get('mac');
			}

			$mgr = new BStationManager(URCValues::WAIT_SEC_SEARCH);
			$result = $mgr->customSearchDevice($sip_user->sip_id, $controllerId, $deviceType, $deviceMac);

			if($result == false) {
				return Response::json(array('result' => false, 'error' => $mgr->getErrResult()));
			}

			$encKey = $this->genSearchKey($this->usr_id, $result);

			return Response::json(array('result' => true, 'data' => $result, 'searchKey' => $encKey));
		}

		if($deviceType == 'TRF-ZW1') {

			$systemId = Input::get('systemId');
			$controllerId = URCSystemData::getControllerId($this->usr_id/*//JWT->Auth::id()*/, $systemId);
			if($controllerId === false) {
				return Response::json(array('result' => false, 'error' => 'not valid'));
			}

			$sip_user = DB::table('sip_user')->where('controller_id', '=', $controllerId)->first();
			if(!$sip_user) {
				return Response::json(array('result' => false, 'error' => 'Not valid communication account'));
			}

			$deviceMac = 'ffffffffffff';
			if(Input::has('mac')) {
				$deviceMac = Input::get('mac');
			}

			$mgr = new BStationManager(URCValues::WAIT_SEC_SEARCH);
			$result = $mgr->customSearchDeviceTRFZW($sip_user->sip_id, $controllerId, $deviceType, $deviceMac);

			if($result == false) {
				return Response::json(array('result' => false, 'error' => $mgr->getErrResult()));
			}

			$encKey = $this->genSearchKey($this->usr_id, $result);

			return Response::json(array('result' => true, 'data' => $result, 'searchKey' => $encKey));
		}
		
		return Response::json(array('result' => false, 'error' => 'UNKNOWN'));
	}
	
	public function doSearchFromInstaller($deviceType) {

		if(!$this->chkJWTToken($errMsg, $errNo)) {
			return Response::make($errMsg, $errNo);
		}
		
		$deviceType = strtoupper($deviceType);

		$rules = array(
			'userInfo' => 'Required',
			'systemId' => 'Required');

		$v = Validator::make(Input::all(), $rules);
		if($v->fails()) {
			return Response::json(array('result' => false, 'error' => implode("\n", $v->messages()->all())));
		}			

		$userChk = URCSystemData::getUserObject(Input::get('userInfo'));
		if($userChk === false) {
			return Response::json(array('result' => false, 'error' => 'username or password is incorrect.'));
		}
		
		$systemId = Input::get('systemId');
		if(URCValues::isBasestation($deviceType) || URCValues::isRemoteControl($deviceType)) {

			$controllerId = URCSystemData::getControllerId($userChk->id, $systemId);
			if($controllerId === false) {
				return Response::json(array('result' => false, 'error' => 'not valid'));
			}

			$sip_user = DB::table('sip_user')->where('controller_id', '=', $controllerId)->first();
			if(!$sip_user) {
				return Response::json(array('result' => false, 'error' => 'Not valid communication account'));
			}

			$deviceMac = 'ffffffffffff';
			if(Input::has('mac')) {
				$deviceMac = Input::get('mac');
			}

			$mgr = new BStationManager(URCValues::WAIT_SEC_SEARCH);
			$result = $mgr->customSearchDevice($sip_user->sip_id, $controllerId, $deviceType, $deviceMac);

			if($result == false) {
				return Response::json(array('result' => false, 'error' => $mgr->getErrResult()));
			}

			$encKey = $this->genSearchKey($userChk->id, $result);

			return Response::json(array('result' => true, 'data' => $result, 'searchKey' => $encKey));
		}
		
		return Response::json(array('result' => false, 'error' => 'UNKNOWN'));
	}

	public function doFunc($funcType) {

		if(!$this->chkJWTTokenWithLevel(URCValues::LOGIN_USER, $errMsg, $errNo)) {
			return Response::make($errMsg, $errNo);
		}
		if(!$this->chkUser()) {
			return Response::json(array('result' => false, 'error' => 'Invalid user'));
		}
			

		if($funcType === 'learn_start') {

			$systemId = Input::get('systemId');
			$controllerId = URCSystemData::getControllerId($this->usr_id/*//JWT->Auth::id()*/, $systemId);
			if($controllerId === false) {
				return Response::json(array('result' => false, 'error' => 'not valid'));
			}

			$sip_user = DB::table('sip_user')->where('controller_id', '=', $controllerId)->first();
			if(!$sip_user) {
				return Response::json(array('result' => false, 'error' => 'Not valid communication account'));
			}

			$mgr = new BStationManager(URCValues::WAIT_SEC);
			$passwordSip = Crypt::decrypt($sip_user->password);
			$result = $mgr->customLearnStart($sip_user->sip_id, $passwordSip, $this->usr_id, $controllerId);
			if($result == false) {
				return Response::json(array('result' => false, 'error' => $mgr->getErrResult()));	
			}
			
			return Response::json(array('result' => true));

			/* for debugging
			$systemId = Input::get('systemId');
			$controllerId = URCSystemData::getControllerId($this->usr_id, $systemId);
			if($controllerId === false) {
				return Response::json(array('result' => false, 'error' => 'not valid'));
			}

			return Response::json(array('result' => true));
			*/
		}

		if($funcType === 'learn_data') {

			$systemId = Input::get('systemId');
			$controllerId = URCSystemData::getControllerId($this->usr_id/*//JWT->Auth::id()*/, $systemId);
			if($controllerId === false) {
				return Response::json(array('result' => false, 'error' => 'not valid'));
			}

			$sip_user = DB::table('sip_user')->where('controller_id', '=', $controllerId)->first();
			if(!$sip_user) {
				return Response::json(array('result' => false, 'error' => 'Not valid communication account'));
			}

			$mgr = new BStationManager(URCValues::WAIT_SEC);
			$passwordSip = Crypt::decrypt($sip_user->password);
			$result = $mgr->customGetLearnData($sip_user->sip_id, $passwordSip, $this->usr_id, $controllerId);
			if($result == false) {
				return Response::json(array('result' => false, 'error' => $mgr->getErrResult()));
			}
			
			//ErrorDebug::write('learned : '.$result);
			return Response::json(array('result' => true, 'data' => $result));

			/* for debugging
			$systemId = Input::get('systemId');
			$controllerId = URCSystemData::getControllerId($this->usr_id, $systemId);
			if($controllerId === false) {
				return Response::json(array('result' => false, 'error' => 'not valid'));
			}

			$username = $this->username;
			$password = Crypt::decrypt($this->usr->password);		

			//ErrorDebug::write('learned : '.$result);
			return Response::json(array('result' => true, 'data' => '00001111222233334444'));

			*/
		}


		if($funcType === 'test') {

			$systemId = Input::get('systemId');
			$controllerId = URCSystemData::getControllerId($this->usr_id/*//JWT->Auth::id()*/, $systemId);
			if($controllerId === false) {
				return Response::json(array('result' => false, 'error' => 'not valid'));
			}

			$sip_user = DB::table('sip_user')->where('controller_id', '=', $controllerId)->first();
			if(!$sip_user) {
				return Response::json(array('result' => false, 'error' => 'Not valid communication account'));
			}

			$rules = array(
				'type' => 'Required',
				'addr' => 'Required',
				'port' => 'Required',
				'data' => 'Required',
				'repeat' => 'Required');

			$v = Validator::make(Input::all(), $rules);
			if($v->fails()) {
				return Response::json(array('result' => false, 'error' => implode("\n", $v->messages()->all())));
			}

			$type = Input::get('type');
			$addr = Input::get('addr');
			$port = Input::get('port');
			$data = Input::get('data');
			
			$attr = new stdClass;
			$attr->repeat = Input::get('repeat');
						
			//ErrorDebug::write('repeat:'.$repeat.'addr:'.$addr.'port:'.$port);
			$target = new stdClass;
			$target->type = Input::get('type');//'IR', 'IP'
			//$target->type = 2;
			//$addr = '192.168.128.1';
			//$port = 2200;

			//ErrorDebug::write($type);
			//ErrorDebug::write($addr);
				
			switch($target->type)
			{
			case URCValues::DB_TYPE_IR:
				$target->mac = $addr;
				$target->ir_port = $port;
				$target->ir_type = 0;
				if(Input::has('ir_type')) {
					$target->ir_type = Input::get('ir_type');
				}				
				break;
			case URCValues::DB_TYPE_IP;
			case URCValues::DB_TYPE_UDP;
				$target->ip = $addr;
				$target->port = $port;
				$attr->ramp_start = Input::get('ramp_start');
				$attr->ramp_speed = Input::get('ramp_speed');
				$attr->auto_cr = Input::get('auto_cr');
				break;
			default:
				return Response::json(array('result' => false, 'error' => 'not valid type'));
			}

			$mgr = new BStationManager(URCValues::WAIT_SEC);
			$passwordSip = Crypt::decrypt($sip_user->password);
			$result = $mgr->customTest($sip_user->sip_id, $passwordSip, $controllerId, $target, $attr, $data);
			if($result == false) {
				return Response::json(array('result' => false, 'error' => $mgr->getErrResult()));
			}

			return Response::json(array('result' => true));
		}

		if($funcType === 'status') {

			$systemId = Input::get('systemId');
			$controllerId = URCSystemData::getControllerId($this->usr_id/*//JWT->Auth::id()*/, $systemId);
			if($controllerId === false) {
				return Response::json(array('result' => false, 'error' => 'not valid'));
			}

			$sip_user = DB::table('sip_user')->where('controller_id', '=', $controllerId)->first();
			if(!$sip_user) {
				return Response::json(array('result' => false, 'error' => 'Not valid communication account'));
			}

			$devices = Input::get('devices');

			/*
			$devices = array();
			
			$item = new stdClass;
			$item->mac = BStationManager::getMACFromControllerId($controllerId);
			$devices[] = $item;

			$item = new stdClass;
			$item->mac = '001122334403';
			$devices[] = $item;
			*/

			$mgr = new BStationManager(URCValues::WAIT_SEC);
			$passwordSip = Crypt::decrypt($sip_user->password);
			$result = $mgr->customDeviceStatus($sip_user->sip_id, $passwordSip, $controllerId, $devices);
			if($result == false) {
				return Response::json(array('result' => false, 'error' => $mgr->getErrResult()));
			}

			return Response::json(array('result' => true, 'data' => $result));
		}

		if($funcType == 'firmware_version') {
			
			$rules = array(
				'systemId' => 'Required',
				'deviceType' => 'Required',
				'firmwareType' => 'Required');

			$v = Validator::make(Input::all(), $rules);
			if($v->fails()) {
				return Response::json(array('result' => false, 'error' => implode("\n", $v->messages()->all())));
			}			

			$systemId = Input::get('systemId');			
			$deviceType = Input::get('deviceType');
			$firmwareType = Input::get('firmwareType');

			/*
			if($firmwareType == 'TRF-ZW1') {
				$firmwareType = 201800;
			}
			else if($firmwareType == 'Nest') {
				$firmwareType = 140500;
			}
			else if($firmwareType == 'Sonos') {
				$firmwareType = 191500;
			}
			else if($firmwareType == 'Thermostat') {
				$firmwareType = 140505;
			}
			*/
			
			$controllerId = URCSystemData::getControllerId($this->usr_id, $systemId);
			if($controllerId === false) {
				return Response::json(array('result' => false, 'error' => 'not valid'));
			}

			$sip_user = DB::table('sip_user')->where('controller_id', '=', $controllerId)->first();
			if(!$sip_user) {
				return Response::json(array('result' => false, 'error' => 'Not valid communication account'));
			}

			$foundModel = DB::table('a_db2_models')->join('a_db2_brands', function($join)
			{
				$join->on('a_db2_models.brand_id', '=', 'a_db2_brands.id');
			})->where('a_db2_models.id', '=', $firmwareType)->
				select('a_db2_models.id','a_db2_models.brand_id',
				'a_db2_models.name','a_db2_brands.name AS brand_name')->first();
			if(!$foundModel) {
				return Response::json(array('result' => false, 'error' => 'Not valid firmware type'));
			}

			$firmwareName = $foundModel->brand_name.'_'.$foundModel->name;

			//ErrorDebug::write($firmwareName);

			$firmServerVer = '';						
			if($this->getServerFileVersionInfo($deviceType, $foundModel->name, $firmwareName, $firmServerVer, $errInfo) === false) {
				return Response::json(array('result' => false, 'error' => $errInfo));
			}

			$mgr = new BStationManager(URCValues::WAIT_SEC);
			$passwordSip = Crypt::decrypt($sip_user->password);
			$result = $mgr->customGetVersionInfo($sip_user->sip_id, $passwordSip, $controllerId, $firmwareName);
			if($result == false) {
				//return Response::json(array('result' => false, 'error' => $mgr->getErrResult()));
				$result = 'Unknown';
			}
						
			return Response::json(array('result' => true, 'version' => $firmServerVer, 'run_version' => $result));
		}

		return Response::json(array('result' => false, 'error' => 'UNKNOWN'));
	}

	public function getServerFileVersionInfo($modelType, $firmwareName, $firmwareType, &$firmVer, &$errorInfo) {

		$infoFileName = './file/'.$modelType.'/TWOWAY/'.$firmwareType.'.json';
		if(!file_exists($infoFileName)) { 

			$errorInfo = 'unknown firmware type';
			return false;
		}
		
		$infoJson = file_get_contents($infoFileName);
		$infoData = json_decode($infoJson);
		if(!isset($infoData->files)) {
			$errorInfo = "Wrong firmware information file";			
			return false;
		}

		$infoDataCnt = count($infoData->files);
		if($infoDataCnt < 1) {
			$errorInfo = "Wrong firmware information file";			
			return false;
		}
		
		for($idx = 0; $idx < $infoDataCnt; $idx++) {

			if($infoData->files[$idx]->name == $firmwareName ||
				$infoData->files[$idx]->name == $firmwareType) {
				$firmVer = $infoData->files[$idx]->version;
				return true;
			}
		}

		$errorInfo = "Wrong firmware information file";			
		return false;
	}

	public function genSearchKey($id, $src) {
		
		$encKey = '';

		if(count($src) > 0) {
			$chkData = ((string)$id).'|'.microtime().'|';
			foreach($src as $device) {
				$chkData = $chkData.substr($device->mac, -4).'|'; 
			}
			$encKey = Crypt::encrypt($chkData);
		}

		return $encKey;
	}	
}
