'use strict';
/**
 * @ngdoc controller
 * @name DeviceTypeController
 * @description
 *  device type 선택
 */
app.controller('DeviceTypeController', function ($scope, $state, categories) {
	if (!$scope.device.type) {
		$scope.device.type = {id: categories[0].id, name: categories[0].name, device: categories[0].device};  // 기본값 설정
	}
	$scope.types = categories;

	$scope.doNext = function () {
		$state.go('menu.programming.add-device.device-name');
	};
});

/**
 * @ngdoc controller
 * @name DeviceNameController
 * @description
 *  device name 입력
 */
app.controller('DeviceNameController', function ($scope, $state, $modal, toastr, Database, Rooms) {
	$scope.device.name = angular.copy($scope.device.type.device);

	var getDeviceBrands = function() {
		Database.retrieveDeviceBrands($scope.device.type.name).then(function(data) {
			$state.go('menu.programming.add-device.device-brand');
		}).catch(toastr.error);
	};

	$scope.getBrandsFromDB = getDeviceBrands;

	// 같은 이름의 device name 이 이미 등록되어 있음을 알리는 modal
	var modal = $modal({
		scope: $scope,
		title: 'Duplicate device name',
		container: '.editor-container',
		template: 'views/modal-tpls/duplicate-name.html',
		show: false
	});

	$scope.doNext = function() {
		var deviceNames = _.pluck(Rooms.getDevices($scope.room.id), 'name');
		if (_.contains(deviceNames, $scope.device.name)) {
			modal.$promise.then(modal.show);
		} else {
			getDeviceBrands();
		}
	};
});

/**
 * @ngdoc controller
 * @name DeviceBrandController
 * @description
 *  device brand 선택
 */
app.controller('DeviceBrandController', function ($scope, $state, Database, Devices) {
	$scope.device.brand = null;
	$scope.brands = Database.getBrands();

	$scope.doNext = function () {
		Devices.setCurrentDevice(angular.copy($scope.device));

		$state.go('menu.programming.add-device.device-model');
	};
});

/**
 * @ngdoc controller
 * @name DeviceModelController
 * @description
 *  device popuplar model 선택
 */
app.controller('DeviceModelController', function ($scope, $state, $modal, $http, toastr, popularDevices, Database) {

	$scope.device.model = null;
	$scope.device.info = null;
	$scope.query.value = '';

	$scope.models = popularDevices;
	$scope.models.ir = [];
	$scope.models.ip = [];

	_.forEach(popularDevices.p_ir, function(device, i) {
		device.index = i;
		$scope.models.ir.push(device);
	});

	_.forEach(popularDevices.p_ip, function(device, i) {
		device.index = i;
		$scope.models.ip.push(device);
	});

	if ($scope.models.ir.length) {
		$scope.device.targetType = 1;
	}

	$scope.doNext = function () {
		return Database.getDeviceInfo($scope.device.type.name, $scope.device.brand.name, $scope.device.model.id, $scope.device.targetType, $scope.device.model.type)
			.then(function(data) {
				var attrs = data.attr;
				console.log(attrs);
				if (attrs.codeset === 'ip') {
					$scope.device.targetPort = $scope.device.targetPort || parseInt(attrs.port, 10);
				} else {
					$scope.device.targetPort = 255;
					$scope.device.targetAddr = $scope.room.bstations[0].mac;
				}

				$scope.device.powerOff = false;
				if (data.meta.length) {
					_.each(data.meta, function(meta) {
						if (meta.strid === 'POWER_OFF' || meta.strid === 'POWER_TOGGLE') {
							$scope.device.powerOff = true;
						}
					});
				}

				$state.go('menu.programming.add-device.device-settings');
			})
			.catch(toastr.error);
	};

	// 테스트 팝업 화면 띄우기
	$scope.showTestModal = function() {

		// power on, mute, 나머지 commands 얻기 위해 getDeviceInfo
		Database.getDeviceInfo($scope.device.type.name, $scope.device.brand.name, $scope.device.model.id, $scope.device.targetType, $scope.device.model.type)
			.then(function(data) {
				$scope.device.info = data;
				$scope.device.powerBtn = false;
				$scope.device.powerBtnData = null;
				$scope.device.muteBtn = false;
				$scope.device.muteBtnData = null;

				_.each(data.btns, function(btn) {
					if (btn.def == 'POWER ON' || btn.def == 'POWER TOGGLE') {
						$scope.device.powerBtn = true;
						$scope.device.powerBtnData = btn.cmd;
					}
					if (btn.def == 'MUTE') {
						$scope.device.muteBtn = true;
						$scope.device.muteBtnData = btn.cmd;
					}
				});

				if (data.attr.codeset === 'ip') {
					$scope.device.targetPort = parseInt(data.attr.port, 10);
				} else {
					$scope.device.targetPort = -1;
				}

				var modal = $modal({
					scope: $scope,
					placement: 'top',
					template: 'views/modal-tpls/test-commands.html',
					container: 'body',
					show: false
				});
				modal.$promise.then(modal.show);
			})
			.catch(toastr.error);
	};

	$scope.device.testBstationMac = $scope.room.bstations[0].mac;

	// 테스트 실행
	$scope.btnTest = function(func) {
		var testData = {},
			data;

		if($scope.device.targetType === 2) {
			if (!$scope.device.targetAddr) {
				toastr.error('An IP address is required.');
				return;
			}
		}

		// power on
		if (func == 'power') {
			data = $scope.device.powerBtnData;
		}
		// mute
		else if (func == 'mute') {
			data = $scope.device.muteBtnData;
		}
		// other commands
		else {
			data = func;
		}

		if($scope.device.targetType === 1) {
			testData = { "systemId" : $scope.system.id, "type" : $scope.device.targetType,
				"addr" : $scope.device.testBstationMac, "port" : $scope.device.targetPort, "repeat" : $scope.device.info.attr.rpt_cnt,
				"ir_type": func.type || 0, "data" : data };
		}
		else {
			testData = { "systemId" : $scope.system.id, "type" : $scope.device.targetType,
				"addr" : $scope.device.targetAddr, "port" : $scope.device.targetPort, "repeat" : $scope.device.info.attr.rpt_cnt,
				"ramp_start" : $scope.device.info.attr.ramp_st, "ramp_speed" : $scope.device.info.attr.ramp_sp, "auto_cr" : $scope.device.info.attr.auto_cr,
				"data" : data };
		}

		var jsonTestData = JSON.stringify(testData);

		$http({
			method: 'POST',
			url: '/api/cloud/test',
			data: jsonTestData
		}).
			success(function(data) {
				if(data.result === true) {
					toastr.success('Test command sent');
				}
				else {
					toastr.error(data.error);
				}
			}).
			error(function() {
				toastr.error("Please try again");
			});
	};

	$scope.goSearchModel = function() {
		$state.go('menu.programming.add-device.device-model-search');
	};

	$scope.goAllModels = function() {
		$state.go('menu.programming.add-device.device-model-all');
	};
});

/**
 * @ngdoc controller
 * @name DeviceModelAllController
 * @description
 *  device all model 선택
 */
app.controller('DeviceModelAllController', function ($scope, $state, $modal, $http, toastr, allDevices, Database) {

	$scope.device.model = null;
	$scope.device.info = null;
	$scope.query.value = '';

	$scope.models = allDevices;
	$scope.models.ir = [];
	$scope.models.ip = [];

	_.forEach(allDevices.p_ir, function(device, i) {
		device.index = i;
		$scope.models.ir.push(device);
	});

	_.forEach(allDevices.p_ip, function(device, i) {
		device.index = i;
		$scope.models.ip.push(device);
	});

	if ($scope.models.ir.length) {
		$scope.device.targetType = 1;
	}

	$scope.doNext = function () {
		return Database.getDeviceInfo($scope.device.type.name, $scope.device.brand.name, $scope.device.model.id, $scope.device.targetType, $scope.device.model.type)
			.then(function(data) {
				var attrs = data.attr;
				console.log(attrs);
				if (attrs.codeset === 'ip') {
					$scope.device.targetPort = $scope.device.targetPort || parseInt(attrs.port, 10);
				} else {
					$scope.device.targetPort = 255;
					$scope.device.targetAddr = $scope.room.bstations[0].mac;
				}

				$scope.device.powerOff = false;
				if (data.meta.length) {
					_.each(data.meta, function(meta) {
						if (meta.strid === 'POWER_OFF' || meta.strid === 'POWER_TOGGLE') {
							$scope.device.powerOff = true;
						}
					});
				}

				$state.go('menu.programming.add-device.device-settings');
			})
			.catch(toastr.error);
	};

	// 테스트 팝업 화면 띄우기
	$scope.showTestModal = function() {

		// power on, mute, 나머지 commands 얻기 위해 getDeviceInfo
		Database.getDeviceInfo($scope.device.type.name, $scope.device.brand.name, $scope.device.model.id, $scope.device.targetType, $scope.device.model.type)
			.then(function(data) {
				$scope.device.info = data;
				$scope.device.powerBtn = false;
				$scope.device.powerBtnData = null;
				$scope.device.muteBtn = false;
				$scope.device.muteBtnData = null;

				_.each(data.btns, function(btn) {
					if (btn.def == 'POWER ON' || btn.def == 'POWER TOGGLE') {
						$scope.device.powerBtn = true;
						$scope.device.powerBtnData = btn.cmd;
					}
					if (btn.def == 'MUTE') {
						$scope.device.muteBtn = true;
						$scope.device.muteBtnData = btn.cmd;
					}
				});

				if (data.attr.codeset === 'ip') {
					$scope.device.targetPort = parseInt(data.attr.port, 10);
				} else {
					$scope.device.targetPort = -1;
				}

				var modal = $modal({
					scope: $scope,
					placement: 'top',
					template: 'views/modal-tpls/test-commands.html',
					container: 'body',
					show: false
				});
				modal.$promise.then(modal.show);
			})
			.catch(toastr.error);
	};

	$scope.device.testBstationMac = $scope.room.bstations[0].mac;

	// 테스트 실행
	$scope.btnTest = function(func) {
		var testData = {},
			data;

		if($scope.device.targetType === 2) {
			if (!$scope.device.targetAddr) {
				toastr.error('An IP address is required.');
				return;
			}
		}

		// power on
		if (func == 'power') {
			data = $scope.device.powerBtnData;
		}
		// mute
		else if (func == 'mute') {
			data = $scope.device.muteBtnData;
		}
		// other commands
		else {
			data = func;
		}

		if($scope.device.targetType === 1) {
			testData = { "systemId" : $scope.system.id, "type" : $scope.device.targetType,
				"addr" : $scope.device.testBstationMac, "port" : $scope.device.targetPort, "repeat" : $scope.device.info.attr.rpt_cnt,
				"ir_type": func.type || 0, "data" : data };
		}
		else {
			testData = { "systemId" : $scope.system.id, "type" : $scope.device.targetType,
				"addr" : $scope.device.targetAddr, "port" : $scope.device.targetPort, "repeat" : $scope.device.info.attr.rpt_cnt,
				"ramp_start" : $scope.device.info.attr.ramp_st, "ramp_speed" : $scope.device.info.attr.ramp_sp, "auto_cr" : $scope.device.info.attr.auto_cr,
				"data" : data };
		}

		var jsonTestData = JSON.stringify(testData);

		$http({
			method: 'POST',
			url: '/api/cloud/test',
			data: jsonTestData
		}).
			success(function(data) {
				if(data.result === true) {
					toastr.success('Test command sent');
				}
				else {
					toastr.error(data.error);
				}
			}).
			error(function() {
				toastr.error("Please try again");
			});
	};
});

/**
 * @ngdoc controller
 * @name DeviceModelSearchController
 * @description
 *  device model 검색
 */
app.controller('DeviceModelSearchController', function ($scope, $state, $modal, $http, toastr, Database) {

	$scope.device.model = null;
	$scope.device.info = null;
	$scope.query.value = '';


	$scope.doNext = function () {
		return Database.getDeviceInfo($scope.device.type.name, $scope.device.brand.name, $scope.device.model.id, $scope.device.targetType, $scope.device.model.type)
			.then(function(data) {
				var attrs = data.attr;
				console.log(attrs);
				if (attrs.codeset === 'ip') {
					$scope.device.targetPort = $scope.device.targetPort || parseInt(attrs.port, 10);
				} else {
					$scope.device.targetPort = 255;
					$scope.device.targetAddr = $scope.room.bstations[0].mac;
				}

				$scope.device.powerOff = false;
				if (data.meta.length) {
					_.each(data.meta, function(meta) {
						if (meta.strid === 'POWER_OFF' || meta.strid === 'POWER_TOGGLE') {
							$scope.device.powerOff = true;
						}
					});
				}

				$state.go('menu.programming.add-device.device-settings');
			})
			.catch(toastr.error);
	};

	// 테스트 팝업 화면 띄우기
	$scope.showTestModal = function() {

		// power on, mute, 나머지 commands 얻기 위해 getDeviceInfo
		Database.getDeviceInfo($scope.device.type.name, $scope.device.brand.name, $scope.device.model.id, $scope.device.targetType, $scope.device.model.type)
			.then(function(data) {
				$scope.device.info = data;
				$scope.device.powerBtn = false;
				$scope.device.powerBtnData = null;
				$scope.device.muteBtn = false;
				$scope.device.muteBtnData = null;

				_.each(data.btns, function(btn) {
					if (btn.def == 'POWER ON' || btn.def == 'POWER TOGGLE') {
						$scope.device.powerBtn = true;
						$scope.device.powerBtnData = btn.cmd;
					}
					if (btn.def == 'MUTE') {
						$scope.device.muteBtn = true;
						$scope.device.muteBtnData = btn.cmd;
					}
				});

				if (data.attr.codeset === 'ip') {
					$scope.device.targetPort = parseInt(data.attr.port, 10);
				} else {
					$scope.device.targetPort = -1;
				}

				var modal = $modal({
					scope: $scope,
					placement: 'top',
					template: 'views/modal-tpls/test-commands.html',
					container: 'body',
					show: false
				});
				modal.$promise.then(modal.show);
			})
			.catch(toastr.error);
	};

	$scope.device.testBstationMac = $scope.room.bstations[0].mac;

	// 테스트 실행
	$scope.btnTest = function(func) {
		var testData = {},
			data;

		if($scope.device.targetType === 2) {
			if (!$scope.device.targetAddr) {
				toastr.error('An IP address is required.');
				return;
			}
		}

		// power on
		if (func == 'power') {
			data = $scope.device.powerBtnData;
		}
		// mute
		else if (func == 'mute') {
			data = $scope.device.muteBtnData;
		}
		// other commands
		else {
			data = func;
		}

		if($scope.device.targetType === 1) {
			testData = { "systemId" : $scope.system.id, "type" : $scope.device.targetType,
				"addr" : $scope.device.testBstationMac, "port" : $scope.device.targetPort, "repeat" : $scope.device.info.attr.rpt_cnt,
				"ir_type": func.type || 0, "data" : data };
		}
		else {
			testData = { "systemId" : $scope.system.id, "type" : $scope.device.targetType,
				"addr" : $scope.device.targetAddr, "port" : $scope.device.targetPort, "repeat" : $scope.device.info.attr.rpt_cnt,
				"ramp_start" : $scope.device.info.attr.ramp_st, "ramp_speed" : $scope.device.info.attr.ramp_sp, "auto_cr" : $scope.device.info.attr.auto_cr,
				"data" : data };
		}

		var jsonTestData = JSON.stringify(testData);

		$http({
			method: 'POST',
			url: '/api/cloud/test',
			data: jsonTestData
		}).
			success(function(data) {
				if(data.result === true) {
					toastr.success('Test command sent');
				}
				else {
					toastr.error(data.error);
				}
			}).
			error(function() {
				toastr.error("Please try again");
			});
	};
});

/**
 * @ngdoc controller
 * @name DeviceSettingsController
 * @description
 *  device 정보 설정 후 생성
 */
app.controller('DeviceSettingsController', function ($rootScope, $scope, $state, toastr, types, Systems, Database, Devices) {
  if ($rootScope.virtualEditor) {
    $scope.wireless_ir_port = 1;
    $scope.irPortOptions = [{name: 'All', value: 255}, {name: '1', value: 1}, {name: '2', value: 2}, {
      name: '3',
      value: 3
    }, {name: '4', value: 4}];
  } else {
    var bstationType = $scope.room.bstations[0].type,
      irInfo = _.find(types, {name: bstationType});

    $scope.wireless_ir_port = irInfo.wireless_ir_port;

    if (irInfo.wired_ir_port_all && irInfo.wired_ir_port == 4) {
      $scope.irPortOptions = [{name: 'All', value: 255}, {name: '1', value: 1}, {name: '2', value: 2}, {
        name: '3',
        value: 3
      }, {name: '4', value: 4}];
    } else if (irInfo.wired_ir_port_all && irInfo.wired_ir_port == 5) {
      $scope.irPortOptions = [{name: 'All', value: 255}, {name: '1', value: 1}, {name: '2', value: 2}, {
        name: '3',
        value: 3
      }, {name: '4', value: 4}, {name: '5', value: 5}];
    } else if (!irInfo.wired_ir_port_all && irInfo.wired_ir_port == 4) {
      $scope.irPortOptions = [{name: '1', value: 1}, {name: '2', value: 2}, {name: '3', value: 3}, {
        name: '4',
        value: 4
      }];
    } else if (!irInfo.wired_ir_port_all && irInfo.wired_ir_port == 5) {
      $scope.irPortOptions = [{name: '1', value: 1}, {name: '2', value: 2}, {name: '3', value: 3}, {
        name: '4',
        value: 4
      }, {name: '5', value: 5}];
    }
  }

	$scope.ir = {target:0, port:255};
	$scope.ir.target = ($scope.device.targetPort ? 1:2);
	$scope.ir.port = ($scope.device.targetPort  ? $scope.device.targetPort :255);

	$scope.isEntDevice = Database.checkIfEntertainment($scope.device.type.name);

	$scope.doNext = function () {
		if($scope.device.targetType === 1) {	
			console.log('ir.target = ', $scope.ir.target);
			if(1 == $scope.ir.target  )
				$scope.device.targetPort  = $scope.ir.port ;
			else
				$scope.device.targetPort  = 0;
		}
		console.log($scope.device.targetPort );

		if ($scope.isEntDevice) {   // entertainment device 인 경우

			$state.go('menu.programming.add-device.favchannels-option');

		} else {  // entertainment device 가 아닌 경우
			var d = angular.copy($scope.device);
			d.favEnable = 0;
			d.favDelay = 400;
			d.favEnter = 0;
			d.type = d.type.name;
			d.brand = d.brand.name;
			d.dbType = parseInt(d.model.type, 10);
			d.modelId = parseInt(d.model.id, 10);
			d.model = d.model.name;
			var jsonData = JSON.stringify(d);

			// device 생성
			return Devices.createOne($scope.room.id, jsonData)
				.then(function(data) {
					console.log(data);
					var id = Systems.getCurrentSystem().id;
					return Systems.updateSystem(id);  
				})
				.then(function (data) {
					$state.transitionTo('menu.programming.options', null, { reload: true, inherit: true, notify: true  });
					toastr.success('Successfully added ' + d.name + '.');
				})
				.catch(toastr.error);
		}
	};
});

/**
 * @ngdoc controller
 * @name FavChannelsOptionController
 * @description
 *  favorite channels 설정
 */
app.controller('FavChannelsOptionController', function ($scope, $state, $modal, toastr, Systems, Devices) {

	$scope.device.favEnable = $scope.device.favEnable || 1;
	$scope.device.favDelay = $scope.device.favDelay || 400;
	$scope.device.favEnter = $scope.device.favEnter || 1;

	$scope.finish = function () {

		var d = angular.copy($scope.device);
		d.type = d.type.name;
		d.brand = d.brand.name;
		d.dbType = parseInt(d.model.type, 10);
		d.modelId = parseInt(d.model.id, 10);
		d.model = d.model.name;

		var jsonData = JSON.stringify(d);
		console.log(jsonData);

		// device 생성
		return Devices.createOne($scope.room.id, jsonData)
			.then(function(data) {
				console.log(data);
				var id = Systems.getCurrentSystem().id;
				return Systems.updateSystem(id);  
			})
			.then(function (data) {
				$state.transitionTo('menu.programming.options', null, { reload: true, inherit: true, notify: true  });
				toastr.success('Successfully added ' + d.name + '.');
			})
			.catch(toastr.error);
	};
});
