'use strict';
/**
 * @ngdoc controller
 * @name NewOrExistingController
 * @description
 *  existing device, new device 선택 화면
 */
app.controller('NewOrExistingController', function ($scope, $state) {
	
	$scope.doNext = function() {
		if ($scope.learnIr.exists) {
			$state.go('menu.advanced.learn-ir.select-device');   
		} else {
			$state.go('menu.advanced.learn-ir.new-device');
		}
	};
});

/**
 * @ngdoc controller
 * @name ExistingDeviceController
 * @description
 *  room, device 선택 화면
 */
app.controller('ExistingDeviceController', function ($scope, $state, toastr, Devices) {
	
	$scope.doNext = function() {
		// device 정보 얻기
		Devices.getOne($scope.learnIr.roomId, $scope.learnIr.deviceId).then(function (data) {
			Devices.setCurrentData(data);
			$state.go('menu.advanced.learn-ir.edit');
		}).catch(toastr.error);
	};
});

/**
 * @ngdoc controller
 * @name NewDeviceController
 * @description
 *  새 device 정보 입력 화면
 */
app.controller('NewDeviceController', function ($scope, $state, Devices, categories) {
	$scope.types = _.pluck(categories, 'name');
	$scope.learnIr.room = _.find($scope.system.rooms, {'id': $scope.room.id});
	$scope.learnIr.device = { target: {} }; 
	$scope.learnIr.device.category = categories[0].name;
	$scope.learnIr.device.target.type = 1;
	$scope.learnIr.device.target.port = 255;
	//$scope.learnIr.device.target.addr = null;
	//$scope.learnIr.device.target.addr = $scope.learnIr.room.bstations[0].mac;

	$scope.doNext = function () {
		var tempDeviceData = { id: '-1', name: $scope.learnIr.device.name, meta_in_toggle: -1, meta_pwr_toggle: -1, meta_pwr_on: -1, meta_pwr_off: -1,  repeat: {min: 1, macro: 3}, dbCon: [], dbKey: [] };
		Devices.initHardBtnPages();
		Devices.addHardBtnProps(tempDeviceData);
		Devices.setCurrentData(tempDeviceData);
		$state.go('menu.advanced.learn-ir.edit');
	};
});

/**
 * @ngdoc controller
 * @name EditIrController
 * @description
 *  button learn 화면
 */
app.controller('EditIrController', function ($scope, $state, toastr, Devices, Systems) {
	

	function handleSuccess(data) {
		$state.go('menu.advanced.options');
	}

	function handleError(error) {
		toastr.error(error, 'Error');
	}

	$scope.goBack = function() {
		if ($scope.learnIr.exists) {
			$state.go('menu.advanced.learn-ir.select-device');   
		} else {
			$state.go('menu.advanced.learn-ir.new-device');
		}
	};

	$scope.finish = function() {
		var pages = [],
				hardPages = angular.copy($scope.learnIr.hard.pages),
				hardBtns = _.flatten(hardPages, 'btns'),
				menuPages = angular.copy($scope.learnIr.menu.pages),
				pageId = 0,
				buttonId = 8192;

		function rewriteMacro(btn) {
			var newMacro = {};
			if(btn.macro) {
				///Devices Service의 getOne function을 통해 Device정보를 얻어 올때 각 button의 macro data를 object로 변환하였으나
				///혹시 몰라서 macro가 string type인 경우에 대해서도 처리.
				newMacro = angular.isObject(btn.macro) ? btn.macro[0] : JSON.parse(btn.macro)[0];
			}

			if(btn.func) {
				if (_.isEmpty(newMacro)) {
					newMacro.type = 1;
					newMacro.device_id = parseInt($scope.learnIr.deviceData.id, 10);
				}

				console.log('rewriteMacro-btn=', btn);
			
				newMacro.func = btn.func.id;

				if (btn.repeatSetting === 'custom') {
					newMacro.repeat_min = btn.repeat_min;
					newMacro.repeat_macro = btn.repeat_macro;
				} else {
					delete newMacro.repeat_min;
					delete newMacro.repeat_macro;
				}

				if (!btn.press_hold) {
					newMacro.press_hold = 0;
				} else {
					newMacro.press_hold = 1;
				}
			}

			//console.log('rewriteMacro- newMacro=', newMacro);
			return JSON.stringify([newMacro]);
		}

		_.remove(hardBtns, function(button) {
			return !button.display_text;
		});

		_.forEach(hardBtns, function(hardBtn) {
			hardBtn.macro = rewriteMacro(hardBtn);
			hardBtn.page_btn_idx = -1;
			delete hardBtn.func;
			delete hardBtn.repeatSetting;
			delete hardBtn.repeat_min;
			delete hardBtn.repeat_macro;
			delete hardBtn.press_hold;
			delete hardBtn.name;
		});


		pages.push({ id: -1, btns: hardBtns });

		_.forEach(menuPages, function(page) {
			if (_.filter(page.btns, 'display_text').length) {
				page.id = pageId;
				pageId++;

				_.remove(page.btns, function(button) {
					return !button.display_text;
				});

				_.forEach(page.btns, function(btn) {

					if (btn.display_text) {

						btn.id = buttonId;
						buttonId++;

						btn.hidden = (true == btn.hidden ? 1:0);
						
						btn.macro = rewriteMacro(btn);

						delete btn.func;
						delete btn.repeatSetting;
						delete btn.repeat_min;
						delete btn.repeat_macro;
						delete btn.press_hold;
					}

				});

				pages.push(page);
			}
		});

		var data = angular.copy($scope.learnIr.deviceData); 

		data.meta_pwr_on =  data.meta_pwr_on || -1;
		data.meta_pwr_off = data.meta_pwr_off || -1;
		data.meta_pwr_toggle = data.meta_pwr_toggle || -1;
		data.meta_in_toggle = data.meta_in_toggle || -1;
		
		var jsonData;
		
		if ($scope.learnIr.exists) {
			_.assign(data, {pages: pages});    
			jsonData = JSON.stringify({ data: data });
			Devices.storeOne($scope.learnIr.roomId, $scope.learnIr.deviceId, jsonData).then(handleSuccess, handleError);
		} else {
			var device = $scope.learnIr.device;
			_.assign(data, { pages: pages, 
											 name: device.name,
											 category: device.category,
											 brand: device.brand,
											 model: device.model,
											 target: device.target
										 });
			jsonData = JSON.stringify({ data: data });
			console.log(data);

			// learn device 생성
			Devices.createCustomOne($scope.learnIr.room.id, jsonData)
			.then(function(data) {
				var id = Systems.getCurrentSystem().id;
				return Systems.updateSystem(id);
			})
			.then(handleSuccess)
			.catch(handleError);
		}

	};

	var currentRoom;
	if ($scope.$parent.learnIr && $scope.$parent.learnIr.room) {
		currentRoom = $scope.$parent.learnIr.room;
		console.log('currentRoom', currentRoom);
	} else if ($scope.learnIr) {
		currentRoom = _.where($scope.system.rooms, {
			id: $scope.learnIr.roomId
		})[0];
	}

	if (currentRoom) {
		var masterBstation = _.where(currentRoom.bstations, {
			master: 1
		})[0];
console.log('masterBstation', masterBstation);
		$scope.masterBstaion = masterBstation;
	}
});
