<?php

require_once('URCSystemData.php');
require_once('DataGenerator.php');
require_once('URCTemplateData.php');

class DealerSystemController extends BaseController {

	public function doRoomControl($funcType, $tRoomId = -1) {

		$dealer_id = '';
		$dealer_grp_id = '';
		$dealer_grp_name = '';
		if(!URCJWTWork::chkJWTTokenDealer($dealer_id, $dealer_grp_id, $dealer_grp_name, $errMsg, $errNo)) {
			return Response::make($errMsg, $errNo);
		}

		
		if($funcType == 'list') {
			
			$urcTemplate = new URCTemplateData($dealer_grp_id, $dealer_id);//JWT->Auth::id());
			$templates = $urcTemplate->getTemplateList();

			foreach($templates as $obj) {
				unset($obj->owner);
			}
			
			return Response::json(array('result' => true, 'templates' => $templates));
		}

		if($funcType == 'create_from_existing') {

			$rules = array(
				'roomId' => 'Required|Integer',
				'name' => 'Required');

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

			$roomId = Input::get('roomId');
			$name = Input::get('name');
			
			if(!URCSystemData::isValidRoomForDealer2($dealer_grp_id, $roomId, $system, $room)) {
				$errMsg = "not valid for this dealer";
				return Response::json(array('result' => false, 'error' => $errMsg));
			}

			$urcTDevice = new URCTemplateData($dealer_grp_id, $dealer_id);
			$result = $urcTDevice->save($system->id, $roomId, $name, $errMsg);
			if($result === false) {
				return Response::json(array('result' => false, 'error' => $errMsg));
			}

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

		if($funcType == 'copy_from_template') {

			if($tRoomId < 0) {
				return Response::json(array('result' => false, 'error' => 'room Id is wrong'));
			}

			$rules = array(
				'roomId' => 'Required|Integer');

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

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

			if(!URCTRoomData::isValidRoom($dealer_id, $roomId)) {
				$errMsg = "not valid for this dealer";
				return Response::json(array('result' => false, 'error' => $errMsg));
			}

			$urcTDevice = new URCTemplateData($dealer_grp_id, $dealer_id);
			$result = $urcTDevice->copyFromTemplate($tRoomId, $roomId, $errMsg);
			if($result === false) {
				return Response::json(array('result' => false, 'error' => $errMsg));
			}

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

		if($funcType == 'create') {
			
			$rules = array(
				'name' => 'Required');

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

			$roomName = Input::get('name');

			$urcTRoom = new URCTRoomData($dealer_id);
			if($urcTRoom->isOverRoomCount()) {
				return Response::json(array('result' => false, 'error' => 'A maximum of templates may be added.'));
			}
			
			$roomId = $urcTRoom->createRoom($roomName, 'a');
			if($roomId < 0) {
				return Response::json(array('result' => false, 'error' => 'room creation fail'));
			}
			
			return Response::json(array('result' => true, 'roomId' => $roomId));
		}

		//after creating, must be check valid
		if(!URCTRoomData::isValidRoom($dealer_id, $tRoomId)) {
			return Response::json(array('result' => false, 'error' => 'not valid for this user' ));
		}

		if($funcType == 'apply_to_new') {

			if($tRoomId < 0) {
				return Response::json(array('result' => false, 'error' => 'room Id is wrong'));
			}

			$rules = array(
				'systemId' => 'Required',
				'name' => 'Required',
				'type' => 'Required',
				'bstationName' => 'Required',
				'bstationMac' => 'Required|min:12');

			$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');
			$roomName = Input::get('name');
			$bstationType = Input::get('type');
			$bstationName = Input::get('bstationName');
			$bstationMac = Input::get('bstationMac');

			$urcTemplate = new URCTemplateData($dealer_grp_id, $dealer_id);
			$result = $urcTemplate->applyNew($tRoomId, $systemId, $bstationType, $bstationName, $bstationMac, $roomName, $errMsg);
			
			//ErrorDebug::write('room');
			//ErrorDebug::write(json_encode($room));

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

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

		if($funcType == 'apply_to_existing') {

			if($tRoomId < 0) {
				return Response::json(array('result' => false, 'error' => 'room Id is wrong'));
			}

			$rules = array(
				'roomId' => 'Required',
				'name' => 'Required');

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

			$roomId = Input::get('roomId');
			$roomName = Input::get('name');

			$urcTemplate = new URCTemplateData($dealer_grp_id, $dealer_id);
			$result = $urcTemplate->applyExisting($tRoomId, $roomId, $roomName, $errMsg);
			
			//ErrorDebug::write('room');
			//ErrorDebug::write(json_encode($room));

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

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

		if($funcType == 'get') {

			if($tRoomId < 0) {
				return Response::json(array('result' => false, 'error' => 'room Id is wrong'));
			}

			$urcTRoom = new URCTRoomData($dealer_id);
			$room = $urcTRoom->getRoom($tRoomId);

			//ErrorDebug::write('room');
			//ErrorDebug::write(json_encode($room));

			if($room === false) {
				return Response::json(array('result' => false, 'error' => 'not exist' ));
			}

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

		if($funcType == 'delete') {

			if($tRoomId < 0) {
				return Response::json(array('result' => false, 'error' => 'room Id is wrong'));
			}

			$urcTRoom = new URCTRoomData($dealer_id);
			$result = $urcTRoom->destroyRoom($tRoomId);

			if($result === false) {
				return Response::json(array('result' => false, 'error' => 'fail to delete room' ));
			}

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

		}

		if($funcType == 'edit') {
			if($tRoomId < 0) {
				return Response::json(array('result' => false, 'error' => 'room Id is wrong'));
			}

			$rules = array(
				'name' => 'Required');

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

			$roomName = Input::get('name');

			$urcTRoom = new URCTRoomData($dealer_id);
			$result = $urcTRoom->editRoom($tRoomId, $roomName);

			if($result === false) {
				return Response::json(array('result' => false, 'error' => 'fail to edit room' ));
			}

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

		if($funcType == 'get_vars') {
			
			if($tRoomId < 0) {
				return Response::json(array('result' => false, 'error' => 'room Id is wrong'));
			}

			$urcTRoom = new URCTRoomData($dealer_id);//JWT->Auth::id());
			$vars = $urcTRoom->getVariables($tRoomId);

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

		if($funcType == 'add_var') {
			
			if($tRoomId < 0) {
				return Response::json(array('result' => false, 'error' => 'room Id is wrong'));
			}

			$rules = array(
				'type' => 'Required',
				'name' => 'Required',
				'value' => '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');
			$name = Input::get('name');
			$value = Input::get('value');

			$errMsg = '';
			$urcTRoom = new URCTRoomData($dealer_id);//JWT->Auth::id());
			$result = $urcTRoom->addVariable($tRoomId, $name, $type, $value, $errMsg);
			if($result === false) {
				return Response::json(array('result' => false, 'error' => $errMsg));
			}

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

		if($funcType == 'del_var') {
			
			if($tRoomId < 0) {
				return Response::json(array('result' => false, 'error' => 'room Id is wrong'));
			}

			$rules = array(
				'id' => 'Required');

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

			$varId = Input::get('id');

			$urcTRoom = new URCTRoomData($dealer_id);//JWT->Auth::id());
			$urcTRoom->delVariables($tRoomId, $varId);

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

		if($funcType == 'edit_var') {
			
			if($tRoomId < 0) {
				return Response::json(array('result' => false, 'error' => 'room Id is wrong'));
			}

			$rules = array(
				'id' => 'Required',
				'type' => 'Required',
				'name' => 'Required',
				'value' => 'Required');

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

			$varId = Input::get('id');
			$type = Input::get('type');
			$name = Input::get('name');
			$value = Input::get('value');

			$errMsg = '';
			$urcTRoom = new URCTRoomData($dealer_id);//JWT->Auth::id());
			$result = $urcTRoom->setVariable($tRoomId, $varId, $name, $type, $value, $errMsg);
			if($result === false) {
				return Response::json(array('result' => false, 'error' => $errMsg));
			}

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

		if($funcType == 'get_events') {
			
			if($tRoomId < 0) {
				return Response::json(array('result' => false, 'error' => 'room Id is wrong'));
			}

			$scheTObj = new URCTScheEventData($dealer_id, $tRoomId);
			$events = $scheTObj->getEvents();

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

		if($funcType == 'store_events') {

			$rules = array(
				'data' => 'Required');

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

			if($tRoomId < 0) {
				return Response::json(array('result' => false, 'error' => 'room Id is wrong'));
			}

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

			$scheTObj = new URCTScheEventData($dealer_id, $tRoomId);
			if($scheTObj->storeEvents($data) === false) {
				return Response::json(array('result' => false, 'error' => 'fail to store'));
			}

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

		if($funcType == 'get_event') {

			$rules = array(
				'id' => 'Required');

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

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

			$scheTObj = new URCTScheEventData($dealer_id, $tRoomId);
			$result = $scheTObj->getEvent($id);
			if($result === false) {
				return Response::json(array('result' => false, 'error' => 'fail to get' ));
			}

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

		if($funcType == 'del_event') {
			
			$rules = array(
				'id' => 'Required');

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

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

			$scheTObj = new URCTScheEventData($dealer_id, $tRoomId);
			$result = $scheTObj->delEvent($id);
			if($result === false) {
				return Response::json(array('result' => false, 'error' => 'fail to delete' ));
			}

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

		if($funcType == 'create_event') {
			
			if($tRoomId < 0) {
				return Response::json(array('result' => false, 'error' => 'room Id is wrong'));
			}

			$rules = array(
				'display_text' => 'Required',
				'macro' => 'Required',
				'default_state' => 'Required',
				'option' => 'Required',
				'day_week' => 'Required',
				'time' => 'Required');

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

			$text = Input::get('display_text');
			$imageName = '';
			if(Input::has('image_name')) {
				$imageName = Input::get('image_name');
			}
			$macro = Input::get('macro');
			$defaultState = Input::get('default_state');
			$option = Input::get('option');
			$dayWeek = Input::get('day_week');
			$time = Input::get('time');

			$scheTObj = new URCTScheEventData($dealer_id, $tRoomId);
			$result = $scheTObj->createEvent($text, $imageName, $macro, $defaultState, $option, $dayWeek, $time);
			if($result === false) {
				return Response::json(array('result' => false, 'error' => 'fail to create' ));
			}

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

		if($funcType == 'set_event') {
			
			if($tRoomId < 0) {
				return Response::json(array('result' => false, 'error' => 'room Id is wrong'));
			}

			$rules = array(
				'id' => 'Required',
				'display_text' => 'Required',
				'macro' => 'Required',
				'default_state' => 'Required',
				'option' => 'Required',
				'day_week' => 'Required',
				'time' => 'Required');

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

			$id = Input::get('id');
			$text = Input::get('display_text');
			$imageName = '';
			if(Input::has('image_name')) {
				$imageName = Input::get('image_name');
			}
			$macro = Input::get('macro');
			$defaultState = Input::get('default_state');
			$option = Input::get('option');
			$dayWeek = Input::get('day_week');
			$time = Input::get('time');

			$scheTObj = new URCTScheEventData($dealer_id, $tRoomId);
			$result = $scheTObj->setEvent($id, $text, $imageName, $macro, $defaultState, $option, $dayWeek, $time);
			if($result === false) {
				return Response::json(array('result' => false, 'error' => 'fail to create' ));
			}

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

		if($funcType == 'set_event_state') {
			
			if($roomId < 0) {
				return Response::json(array('result' => false, 'error' => 'room Id is wrong'));
			}

			$rules = array(
				'id' => 'Required',
				'default_state' => 'Required');

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

			$id = Input::get('id');
			$defaultState = Input::get('default_state');

			$scheTObj = new URCTScheEventData($dealer_id, $tRoomId);
			$result = $scheTObj->setEventStatus($id, $defaultState);
			if($result === false) {
				return Response::json(array('result' => false, 'error' => 'fail to create' ));
			}

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

	public function doDeviceControl($funcType, $roomId, $deviceId = -1) {

		$dealer_id = '';
		$dealer_grp_id = '';
		$dealer_grp_name = '';
		if(!URCJWTWork::chkJWTTokenDealer($dealer_id, $dealer_grp_id, $dealer_grp_name, $errMsg, $errNo)) {
			return Response::make($errMsg, $errNo);
		}

		if(!URCTRoomData::isValidRoom($dealer_id, $roomId)) {
			return Response::json(array('result' => false, 'error' => 'not valid for this user' ));
		}

		if($funcType == 'create') {

			$rules = array(
				'name' => 'Required',
				'type' => 'Required',
				'brand' => 'Required',
				'model' => 'Required',
				'dbType' => 'Required',
				'modelId' => 'Required|Integer',
				'targetType' => 'Required',
				'targetAddr' => 'Required',
				'targetPort' => 'Required|Integer',
				'favEnable' => 'Required',
				'favDelay' => 'Required',
				'favEnter' => 'Required');

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

			$urcTDevice = new URCTDeviceData($roomId);

			$name = Input::get('name');
			$category = Input::get('type');
			$brand = Input::get('brand');
			$model = Input::get('model');
			$dbType = Input::get('dbType');
			$modelId = Input::get('modelId');
			$target = new stdClass;
			$target->type = Input::get('targetType');
			$target->addr = Input::get('targetAddr');
			$target->port = Input::get('targetPort');
			$favOption =  new stdClass;
			$favOption->enable = Input::get('favEnable');
			if($favOption->enable) {
				$favOption->delay =  Input::get('favDelay');
			}
			else {
				$favOption->delay = 400;
			}
			$favOption->enter = Input::get('favEnter');

			//ErrorDebug::write('dbType:'.$dbType);
		
			$deviceId = $urcTDevice->createDevice($this->username, $name, $category, $brand, $model, $dbType, $modelId, $target, $favOption);
			if($deviceId < 0) {
				return Response::json(array('result' => false, 'error' => 'Unable to add this device to your system.'));//'fail to create device' ));
			}

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

		if($funcType == 'create_custom') {

			$urcTDevice = new URCTDeviceData($roomId);
			$deviceData = Input::get('data');
			$deviceId = $urcTDevice->createCustomDevice($deviceData);
			if($deviceId < 0) {
				return Response::json(array('result' => false, 'error' => 'Unable to add this device to your system.'));//'fail to create device' ));
			}
			
			return Response::json(array('result' => true));
		}

		if($funcType == 'delete') {

			if($deviceId < 0) {
				return Response::json(array('result' => false, 'error' => 'device Id is wrong'));
			}

			$urcTDevice = new URCTDeviceData($roomId);
			$result = $urcTDevice->destroyDevice($deviceId);

			if($result === false) {
				return Response::json(array('result' => false, 'error' => 'fail to delete device' ));
			}

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

		}

		if($funcType == 'edit') {

			if($deviceId < 0) {
				return Response::json(array('result' => false, 'error' => 'device Id is wrong'));
			}

			$rules = array(
				'name' => 'Required',
				'targetType' => 'Required',
				'targetPort' => 'Required|Integer',
				'repeatMin' => 'Required|Integer',
				'repeatMacro' => 'Required|Integer');

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


			$deviceName = Input::get('name');

			$target = new stdClass;
			$target->type = Input::get('targetType');
			$target->addr = Input::get('targetAddr');
			$target->port = Input::get('targetPort');

			$attr = new stdClass;
			$attr->repeat_min = Input::get('repeatMin');
			$attr->repeat_macro = Input::get('repeatMacro');
			if($target->type == URCValues::DB_TYPE_IP ||
				$target->type == URCValues::DB_TYPE_UDP) {
				$attr->ramp_start = Input::get('rampStart');
				$attr->ramp_speed = Input::get('rampSpeed');
				$attr->auto_cr = Input::get('autoCr');	
			}

			$urcTDevice = new URCTDeviceData($roomId);
			$result = $urcTDevice->editDevice($deviceId, $deviceName, $target, $attr);

			if($result === false) {
				return Response::json(array('result' => false, 'error' => 'fail to edit device' ));
			}

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

		if($funcType == 'favorite') {

			if($deviceId < 0) {
				return Response::json(array('result' => false, 'error' => 'device Id is wrong'));
			}

			$favOption = Input::get('favOption');
			$favDelay = Input::get('favDelay');
			$favEnter = Input::get('favEnter');

			$urcTDevice = new URCTDeviceData($roomId);
			$result = $urcTDevice->setFavoriteDevice($deviceId, $favOption, URCValues::FAV_DELAY_CHANGE, $favDelay, $favEnter);

			if($result === false) {
				return Response::json(array('result' => false, 'error' => 'fail to set the favorite option' ));
			}

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

		if($funcType == 'get_punch') {

			if($deviceId < 0) {
				return Response::json(array('result' => false, 'error' => 'device Id is wrong'));
			}

			$urcTDevice = new URCTDeviceData($roomId);
			$result = $urcTDevice->getPunchDevice($deviceId);

			if($result === false) {
				return Response::json(array('result' => false, 'error' => 'fail to punch' ));
			}

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

		if($funcType == 'punch') {

			if($deviceId < 0) {
				return Response::json(array('result' => false, 'error' => 'device Id is wrong'));
			}

			$deviceFrom = Input::get('punchFrom');

			$urcTDevice = new URCTDeviceData($roomId);
			$result = $urcTDevice->setPunchDevice($deviceFrom, $deviceId);

			if($result === false) {
				return Response::json(array('result' => false, 'error' => 'fail to punch' ));
			}

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

		if($funcType == 'punch_multi') {

			$rules = array(
				'punchFrom' => 'Required',
				'punchTo' => 'Required');

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

			$deviceFrom = Input::get('punchFrom');
			$devicesTo = Input::get('punchTo');

			$urcTDevice = new URCTDeviceData($roomId);
			$result = $urcTDevice->setPunchDevices($deviceFrom, $devicesTo);

			if($result === false) {
				return Response::json(array('result' => false, 'error' => 'fail to punch' ));
			}

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

		if($funcType == 'get_con_dev') {

			$urcTDevice = new URCTDeviceData($roomId);
			$data = $urcTDevice->getConDevData($deviceId);
			foreach($data as $func) {
				unset($func->device_id);
				unset($func->room_id);
			}

			//$metaData = $urcDevice->getMetaData($deviceId);

			if(!$data || count($data) <= 0) {// || $metaData === false) {
				return Response::json(array('result' => false, 'error' => 'no connected device data' ));
			}

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

		if($funcType == 'get_main') {

			$urcTDevice = new URCTDeviceData($roomId);

			$mainDeviceId = $urcTDevice->getMainDeviceId();
			$device = $urcTDevice->getDevice($mainDeviceId, true);

			//ErrorDebug::write('main');
			//ErrorDebug::write(json_encode($device));

			if($device === false) {
				return Response::json(array('result' => false, 'error' => 'not exist'.$roomId.' '.$mainDeviceId ));
			}

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

		if($funcType == 'store_main') {

			$deviceData = Input::get('data');
			$urcTDevice = new URCTDeviceData($roomId);

			$mainDeviceId = $urcTDevice->getMainDeviceId();
			$result = $urcTDevice->storeDevice($mainDeviceId, $deviceData, true);

			if($result === false) {
				return Response::json(array('result' => false, 'error' => "couldn't save" ));
			}

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

		if($funcType == 'get') {

			if($deviceId < 0) {
				return Response::json(array('result' => false, 'error' => 'device Id is wrong'));
			}

			$urcTDevice = new URCTDeviceData($roomId);

			$device = $urcTDevice->getDevice($deviceId, false);

			//ErrorDebug::write('device');
			//ErrorDebug::write(json_encode($device));

			if($device === false) {
				return Response::json(array('result' => false, 'error' => 'not exist'.$roomId.' '.$deviceId ));
			}

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

		if($funcType == 'store') {
			
			if($deviceId < 0) {
				return Response::json(array('result' => false, 'error' => 'device Id is wrong'));
			}

			$device = DB::table('a_t_devices')->where('room_id', '=', $roomId)->
	 			where('id', '=', $deviceId)->first();
	 		if($device && $device->dev_type != 0) {
	 			return Response::json(array('result' => false, 'error' => "couldn't save" ));
	 		}

			$deviceData = Input::get('data');
			$urcTDevice = new URCTDeviceData($roomId);

			$result = $urcTDevice->storeDevice($deviceId, $deviceData, false);

			if($result === false) {
				return Response::json(array('result' => false, 'error' => "couldn't save" ));
			}

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

	public function doButtonControl($funcType, $roomId, $deviceId = -1, $buttonId = -1) {

		$dealer_id = '';
		$dealer_grp_id = '';
		$dealer_grp_name = '';
		if(!URCJWTWork::chkJWTTokenDealer($dealer_id, $dealer_grp_id, $dealer_grp_name, $errMsg, $errNo)) {
			return Response::make($errMsg, $errNo);
		}

		if(!URCTRoomData::isValidRoom($dealer_id, $roomId)) {
			return Response::json(array('result' => false, 'error' => 'not valid for this user' ));
		}

		if($funcType == 'create') {
			
			$rules = array(
				'edit_type' => 'Required|Integer');

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

			$text = Input::get('text');
			$autoWait = Input::get('auto_wait');
			$activity = Input::get('activity');
			$editType = Input::get('edit_type');
			$popup = Input::get('popup');
			$macro = Input::get('macro');

			if($editType != URCValues::ETYPE_MACRO) {
				return Response::json(array('result' => false, 'error' => 'command error' ));
			}

			if($deviceId < 0) {
				return Response::json(array('result' => false, 'error' => 'no match device' ));
			}

			$urcTBtn = new URCTBtnData($roomId, $deviceId);
			
			$result = $urcTBtn->createBtn($text, $autoWait, $popup, $activity, $macro);

			if($result === false) {
				return Response::json(array('result' => false, 'error' => 'fail to create button' ));
			}


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

		if($funcType == 'get_button_macro_with_device') {

			$urcTDev = new URCTDeviceData($roomId);

			$mainDevId = $urcTDev->getMainDeviceId();

			if($mainDevId < 0 || $deviceId < 0) {
				return Response::json(array('result' => false, 'error' => 'no match device' ));
			}

			$urcTBtn = new URCTBtnData($roomId, $mainDevId);
			$result = $urcTBtn->getMacroFromDevice($deviceId);

			if(!$result) {
				return Response::json(array('result' => false, 'error' => 'no match device' ));
			}

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

		if($funcType == 'delete_button_macro_with_device') {

			$urcTDev = new URCTDeviceData($roomId);

			$mainDevId = $urcTDev->getMainDeviceId();

			if($mainDevId < 0 || $deviceId < 0) {
				return Response::json(array('result' => false, 'error' => 'no match device' ));
			}

			$urcTBtn = new URCTBtnData($roomId, $mainDevId);
			$result = $urcTBtn->delMacroFromDevice($deviceId);

			if(!$result) {
				return Response::json(array('result' => false, 'error' => 'no match device' ));
			}

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

		if($funcType == 'store_button_macro_with_device') {

			$autoWait = Input::get('auto_wait');
			$activity = Input::get('activity');
			$editType = Input::get('edit_type');
			$popup = Input::get('popup');
			$macro = Input::get('macro');

			$urcTDev = new URCTDeviceData($roomId);
			$mainDevId = $urcTDev->getMainDeviceId();

			if($mainDevId < 0 || $deviceId < 0) {
				return Response::json(array('result' => false, 'error' => 'no match device' ));
			}

			$urcTBtn = new URCTBtnData($roomId, $mainDevId);

			$result = $urcTBtn->storeMacroFromDevice($deviceId, $autoWait, $editType, $popup, $activity, $macro);

			if($result === false) {
				return Response::json(array('result' => false, 'error' => 'fail to store activity' ));
			}

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

		if($funcType == 'get_button_macro') {

			$urcTDev = new URCTDeviceData($roomId);

			if($buttonId < 0) {
				return Response::json(array('result' => false, 'error' => 'no match button' ));
			}

			$urcTBtn = new URCTBtnData($roomId, $deviceId);
			$result = $urcTBtn->getMacro($buttonId);

			if(!$result) {
				return Response::json(array('result' => false, 'error' => 'no match button' ));
			}

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

		if($funcType == 'delete_button_macro') {

			$urcTDev = new URCTDeviceData($roomId);

			if($buttonId < 0) {
				return Response::json(array('result' => false, 'error' => 'no match button' ));
			}

			$urcTBtn = new URCTBtnData($roomId, $deviceId);
			$result = $urcTBtn->delMacro($buttonId);

			switch($result)
			{
			case 0:
				return Response::json(array('result' => false, 'error' => 'no match button' ));
			case 2:
				return Response::json(array('result' => true, 'deleted' => true));
			}

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

		if($funcType == 'store_button_macro') {

			$autoWait = Input::get('auto_wait');
			$activity = Input::get('activity');
			$editType = Input::get('edit_type');
			$popup = Input::get('popup');
			$macro = Input::get('macro');

			if($editType != URCValues::ETYPE_MACRO) {
				return Response::json(array('result' => false, 'error' => 'command error' ));
			}

			$urcTDev = new URCTDeviceData($roomId);
			if($buttonId < 0) {
				return Response::json(array('result' => false, 'error' => 'no match button' ));
			}

			$urcTBtn = new URCTBtnData($roomId, $deviceId);

			$result = $urcTBtn->storeMacro($buttonId, $autoWait, $popup, $activity, $macro);

			if($result === false) {
				return Response::json(array('result' => false, 'error' => 'fail to store macro' ));
			}

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

		if($funcType == 'get_power_macro') {

			$urcTBtn = new URCTBtnData($roomId, -1);
			$result = $urcTBtn->getPowerMacro();
			if(!$result) {
				return Response::json(array('result' => false, 'error' => 'no match power' ));
			}

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

		if($funcType == 'delete_power_macro') {

			$urcTBtn = new URCTBtnData($roomId, -1);
			$result = $urcTBtn->delPowerMacro();
			if(!$result) {
				return Response::json(array('result' => false, 'error' => 'no match power' ));
			}

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

		if($funcType == 'store_power_macro') {

			$autoWait = Input::get('auto_wait');
			$activity = Input::get('activity');
			$editType = Input::get('edit_type');
			$popup = Input::get('popup');
			$macro = Input::get('macro');

			$urcTBtn = new URCTBtnData($roomId, -1);
			$result = $urcTBtn->storePowerMacro($autoWait, $editType, $popup, $activity, $macro);

			if($result === false) {
				return Response::json(array('result' => false, 'error' => 'fail to store activity' ));
			}

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

	public function microtime_gap($microTimeSt, $microTimeEd)
	{
	     list($usecSt, $secSt) = explode(" ", $microTimeSt);
	     $stTime = ((float)$usecSt + (float)$secSt);

	     list($usecEd, $secEd) = explode(" ", $microTimeEd);
	     $edTime = ((float)$usecEd + (float)$secEd);

	     return ($edTime - $stTime);
	}

	public function checkSearchKey($key, $userId, $mac) {

		if(strlen($key) < 4) {
			return false;
		}

		try
		{
			$realKey = Crypt::decrypt($key);
		}
		catch(\Exception $e) 
		{
			return false;
		}

		if(!$realKey || strlen($realKey) < 4) {
			return false;
		}

		$subMac = substr($mac, -4);
		$pos = strpos($realKey, $subMac);
		if($pos === false) {
			return false;
		}

		$arData = explode('|', $realKey);
		if(count($arData) < 3) {//0:userId, 1:timestamp, from 2...
			return false;
		}

		if($arData[0] !== ((string)$userId)) {
			return false;
		}

		$seconds = $this->microtime_gap($arData[1], microtime());
		if($seconds < 0 || $seconds > 360) {
			return false;
		}

		return true;
	}
}