'use strict';
/**
 * @ngdoc directive
 * @name hcmEdit
 * @description
 *  system-overview 화면에서 system/room/base station/device 정보 변경
 */
app.directive('hcmEdit', function ($rootScope, $http, $templateCache, $state, $modal, toastr, Devices, Systems, Rooms) {
	
	return {
		restrict: 'EA',
		replace: true,
		scope: {
			system: '=',
			room: '=',
			bstation: '=',
			device: '=',
			ttype: '=',
			type: '@' //takes in a String for edit type (i.e. system, room, device, bstation)
		},

		link: function (scope, element, attrs) {
			var modal, type = scope.type.toLowerCase();

			scope.lightLevels = [ {'value': 0, 'label': 'Off'}, {'value': 1, 'label': 'Low'}, {'value': 2, 'label': 'Medium'}, {'value': 3, 'label': 'High'}];
			scope.irPortOptions = [{name:'All', value:255}, {name:'1', value:1}, {name:'2', value:2}, {name:'3', value:3}, {name:'4', value:4}];

			scope.ir = {target:0, port:255};

			switch (scope.type) {
				case 'system':
					modal = $modal({
						scope: scope,
						title: 'Edit this system',
						template: 'edit-system.html',
						container: '#system-overview',
						show: false
					});

					scope.selections = {
						system: angular.copy(scope.system)
					};
					break;
				case 'room':
					modal = $modal({
						scope: scope,
						title: 'Edit this room',
						template: 'edit-room.html',
						container: '#system-overview',
						show: false
					});

					scope.selections = {
						room: angular.copy(scope.room)
					};
					break;
				case 'device':
					modal = $modal({
						scope: scope,
						title: 'Edit this device',
						//placement: 'top',
						template: 'edit-device.html',
						container: '#system-overview',
						show: false
					});

					scope.selections = {
						room: angular.copy(scope.room),
						device: angular.copy(scope.device)
					};
					scope.selections.device.ramp_start /= 1000;
					scope.selections.device.ramp_speed /= 1000;

					scope.ir.target = (scope.selections.device.target_port ? 1:2);
					scope.ir.port = (scope.selections.device.target_port  ? scope.selections.device.target_port :255);

					console.log('scope.ir.port = ', scope.ir.port);

          if ($rootScope.virtualEditor) {
            scope.wireless_ir_port = 1;
          } else {
            if (scope.room.bstations[0] && scope.room.bstations[0].type) {
              var bstationType = scope.room.bstations[0].type,
                irInfo = _.find(scope.$parent.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}];
              }
            }
          }

					break;
				case 'twoway_device':
          scope.trfZwLink = $rootScope.env.trfZwLink;
          scope.urcPortalUrl = $rootScope.env.urcPortalUrl;

					modal = $modal({
						scope: scope,
						title: 'Edit this device',
						//placement: 'top',
						template: 'edit-twoway-device.html',
						container: '#system-overview',
						show: false
					});

					scope.selections = {
						room: angular.copy(scope.room),
						device: angular.copy(scope.device)
					};

					scope.getTwowayVersion = function(){

						// fw_version
						var currentSystem = Systems.getCurrentSystem();

            var masterBstation;
            _.each(currentSystem.rooms, function(room) {
              if (!masterBstation) {
                masterBstation = _.where(room.bstations, {
                  master: 1
                })[0];
              }
            });

						Systems.getFirmwareVersion(masterBstation.type, scope.selections.device.model_id, currentSystem.id)
							.then(function(data) {
								scope.selections.device.fw_version = data.version;
								scope.selections.device.fw_run_version = data.run_version;

								scope.selectionsInitial = angular.copy(scope.selections);

							})
							.catch(function(error) {
								//toastr.error(error);
							});
					}

          // MAC
					if (scope.ttype & 0x0001) {
						var targetAddrStr = scope.selections.device.target_addr;
						targetAddrStr = targetAddrStr.toUpperCase();		// MAC address 대문자로 변경
						targetAddrStr = targetAddrStr.replace(/:/g, '');
						targetAddrStr = targetAddrStr.slice(0,10).replace(/(.{2})/g,'$1:') + targetAddrStr.slice(10, 12);		// : 추가

						scope.selections.device.target_addr = targetAddrStr;

						// search
						if (scope.ttype & 0x00010000) {
							scope.selections.device.type = 'discovery';
						}
						// mac
						else {
							scope.selections.device.type = 'mac';
						}
					} else {
						// IP
						if (scope.ttype & 0x0002) {
							scope.selections.device.type = 'ip';

							if (!scope.selections.device.ip) {
								scope.selections.device.ip = angular.copy(scope.selections.device.target_addr).split(':')[0];
							}
							if (!scope.selections.device.port) {
								scope.selections.device.port = +angular.copy(scope.selections.device.target_addr).split(':')[1];
							}
						}
						// service
						else if (scope.ttype & 0x0004) {
							scope.selections.device.type = 'service';
						}
					}

          // TRF-ZW data update
          scope.updateTrfzwData = function() {
            _.each(scope.$parent.system.rooms, function(room) {
              var trfzw = _.find(room.twoway_devices, {model: 'TRF-ZW1'});
              if (trfzw) {
                Devices.updateTwowayDevice(room.id, trfzw.id)
                  .then(function(data) {
                    trfzw.data = data;
                  }, function() {
                    var modal = $modal({
                      container: '.editor-container',
                      template: 'views/modal-tpls/connection-problem.html',
                      show: false
                    });

                    modal.$promise.then(modal.show);
                  })
                  .catch(toastr.error);

                return false;
              }
            });

            var updateModal = $modal({
              container: '.editor-container',
              template: 'views/modal-tpls/update-trfzw-data.html',
              show: false
            });

            updateModal.$promise.then(updateModal.show);
            setTimeout(function() {
              updateModal.$promise.then(updateModal.hide);
            }, 3000);
          };

					break;
				case 'bstation':
					modal = $modal({
						scope: scope,
						title: 'Edit this controller',
						template: 'edit-bstation.html',
						container: '#system-overview',
						show: false
					});

					scope.selections = {
						room: angular.copy(scope.room),
						bstation: angular.copy(scope.bstation)
					};
					break;
				case 'default':
					throw new Error('There was an error retrieving information. Please try again. If the error continues please log out and then log in again.');
			}

			scope.editSystem = function(system) {
				var currentSystem = Systems.getCurrentSystem();

				console.log('editSystem called');
				if (!_.isEqual(currentSystem, system)) {
					var jsonData = JSON.stringify( { name : system.name } );
					console.log(jsonData);
					Systems.editSystem(system.id, jsonData).
						then(function(data) {    
							currentSystem.name = system.name;
							Systems.loadSystem(currentSystem);
							$state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
						}).
						catch(toastr.error);
				}
			};

			scope.editRoom = function(room) {
				var currentSystem = Systems.getCurrentSystem();
				var roomIndex = _.findIndex(currentSystem.rooms, { 'id': room.id });
				var currentRoom = currentSystem.rooms[roomIndex];

				if (!_.isEqual(currentRoom, room)) {
					var jsonData = JSON.stringify( { name : room.name } );
					// room 이름 변경
					Rooms.edit(room.id, jsonData).
						then(function(data) {    
							currentRoom.name = room.name;
							Systems.loadSystem(currentSystem);
							$state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
						}).
						catch(toastr.error);
				}
			};


			scope.editBstation = function(room, bstation) {
        if ($rootScope.virtualEditor) {
          toastr.error('This base station cannot be renamed.');
        } else {
          var currentSystem = Systems.getCurrentSystem(),
            roomIndex = _.findIndex(currentSystem.rooms, {'id': room.id}),
            bstationIndex = _.findIndex(currentSystem.rooms[roomIndex].bstations, {'id': bstation.id}),
            currentBstation = currentSystem.rooms[roomIndex].bstations[bstationIndex];

          if (!_.isEqual(currentBstation, bstation)) {
            var jsonData = JSON.stringify({
              name: bstation.name,
              mac: bstation.mac,
              type: bstation.type,
              lightLevel: bstation.light_level
            });
            // base station 의 type, name, lightLevel 을 설정
            Rooms.baseStations('edit', room.id, jsonData).then(function (data) {
              currentBstation.name = bstation.name;
              currentBstation.light_level = bstation.light_level;
              Systems.loadSystem(currentSystem);
              $state.transitionTo($state.current, null, {reload: true, inherit: true, notify: true});
            }).catch(toastr.error);
          }
        }
			};



			scope.editDevice = function(room, device) {
				var currentSystem = Systems.getCurrentSystem(),
								roomIndex = _.findIndex(currentSystem.rooms, { 'id': room.id }),
							deviceIndex = _.findIndex(currentSystem.rooms[roomIndex].devices, { 'id': device.id }),
						currentDevice = currentSystem.rooms[roomIndex].devices[deviceIndex],
						clonedDevice = _.clone(device);

				if(clonedDevice.target_type === 1) {  
					console.log('ir.target = ', scope.ir.target);
					if(1 == scope.ir.target  )
						clonedDevice.target_port  = scope.ir.port ;
					else
						clonedDevice.target_port  = 0;
				}
				console.log('editDevice=', clonedDevice.target_port );
						
				clonedDevice.ramp_start *= 1000;
				clonedDevice.ramp_speed *= 1000;

				if (!_.isEqual(currentDevice, clonedDevice)) {
					var jsonData = JSON.stringify( {
						name : clonedDevice.name,
						targetType : clonedDevice.target_type,
						targetAddr : clonedDevice.target_addr,
						targetPort: clonedDevice.target_port,
						repeatMin: clonedDevice.repeat_min,
						repeatMacro: clonedDevice.repeat_macro,
						rampStart: clonedDevice.ramp_start,
						rampSpeed: clonedDevice.ramp_speed,
						autoCr: clonedDevice.auto_cr
					});

					var url;
					if ($rootScope.virtualEditor) {
						url = '/api/dealer/device/edit/' + room.id + '/' + device.id;
					} else {
						url = '/api/device/edit/' + room.id + '/' + device.id;
					}

					// device 정보 변경 API 호출
					$http({
						method: 'POST',
						url: url,
						data : jsonData
					}).
					success(function(data) {
						if(data.result) {
							_.assign(currentDevice, clonedDevice);
							Systems.loadSystem(currentSystem);
							$state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
						}
						else {
							toastr.error(data.error);
						}
					}).
					error(toastr.error);
				}
			};

      scope.$watch('selections.device', function(newVal, oldVal) {
        if (newVal && typeof newVal.variables !== 'undefined' && typeof newVal.variables === 'object' && newVal.variables != null && newVal.variables.length) {
          newVal.hasVariables = true;
          newVal.varData = [];
          newVal.newVarData = {};

          _.each(newVal.variables, function(item) {
            if (item.attr.match('n')) {
              item.required = true;
            } else {
              item.required = false;
            }

            if (item.attr.match('p')) {
              item.type = 'password';
            } else if (item.attr.match('m')) {
              item.type = 'textarea';
            } else {
              item.type = 'text';
            }

            if (item.attr.match('r')) {
              item.readonly = true;
            } else {
              item.readonly = false;
            }

            if (item.name === 'username') {
              newVal.varUsername = item;
            } else if (item.name === 'password') {
              newVal.varPassword = item;
            } else if (item.name !== 'device_port') {
              newVal.varData.push(item);
            }
          });
        }
      });

      scope.showModal = function(mode) {
        // edit parameter 하는 화면에서 값이 미리 입력되어 있게 하기 위해
        if (mode === 'edit-twoway-username') {
          scope.selections.device.varNewUsername = angular.copy(scope.selections.device.varUsername.value);
        } else if (mode === 'edit-twoway-parameters') {
          _.each(scope.selections.device.varData, function(item) {
            if (!item.attr.match('p')) {
              scope.selections.device.newVarData[item.name] = item.value;
            }
          });
        }
        
        var templateUrl = 'views/modal-tpls/system-overview/' + mode + '.html';

        var modal = $modal({
          scope: scope,
          template: templateUrl,
          container: 'body',
          show: false
        });
        modal.$promise.then(modal.show);
      };

      scope.saveUsername = function() {
        scope.selections.device.varUsername.value = angular.copy(scope.selections.device.varNewUsername);
        scope.selections.device.varPassword.value = angular.copy(scope.selections.device.varNewPassword);
      };

      scope.saveParameters = function() {
        _.each(scope.selections.device.varData, function(item) {
          item.value = scope.selections.device.newVarData[item.name];
        });
      };

      scope.editTwowayDevice = function(room, device, targetType) {
				var currentSystem = Systems.getCurrentSystem(),
					roomIndex = _.findIndex(currentSystem.rooms, { 'id': room.id }),
					deviceIndex = _.findIndex(currentSystem.rooms[roomIndex].twoway_devices, { 'id': device.id }),
					currentDevice = currentSystem.rooms[roomIndex].twoway_devices[deviceIndex],
					clonedDevice = _.clone(device);

				var d = {
						name: scope.selections.device.name,
						targetType: scope.selections.device.target_type,
						targetAddr: '""'
					};

				// MAC
				if (targetType & 0x0001) {
					// search
					if (targetType & 0x00010000) {
						d.targetAddr = scope.selections.device.target_addr;
					}
					// mac
					else {
						d.targetAddr = scope.selections.device.target_addr;
					}

					d.targetAddr = d.targetAddr.replace(/:/g, '');
          d.targetAddr = d.targetAddr.toUpperCase();
				} else {
					// IP
					if (targetType & 0x0002) {
						d.targetAddr = scope.selections.device.ip + ':' + scope.selections.device.port;
					}
					// service
					else if (targetType & 0x0004) {

					}
				}

        // variables 가 있는 device 인 경우
        if (scope.selections.device.hasVariables) {
          scope.selections.device.variables = [];
          if (scope.selections.device.varUsername) {
            var obj = angular.copy(scope.selections.device.varUsername);
            delete(obj['$$hashKey']);
            delete(obj.required);
            delete(obj.readonly);
            delete(obj.type);

            scope.selections.device.variables.push(obj);
          }
          if (scope.selections.device.varPassword) {
            var obj = angular.copy(scope.selections.device.varPassword);
            delete(obj['$$hashKey']);
            delete(obj.required);
            delete(obj.readonly);
            delete(obj.type);

            scope.selections.device.variables.push(obj);
          }
          _.each(scope.selections.device.varData, function(item) {
            var obj = angular.copy(item);
            delete(obj['$$hashKey']);
            delete(obj.required);
            delete(obj.readonly);
            delete(obj.type);

            scope.selections.device.variables.push(obj);
          });

          d.variables = scope.selections.device.variables;
        } else {
          d.variables = '""';
        }

				var jsonData = JSON.stringify(d);

				// device 정보 변경 API 호출
				$http({
					method: 'POST',
					url: '/api/twoway_device/edit/' + room.id + '/' + device.id,
					data : jsonData
				}).
					success(function(data) {
						if(data.result) {
							_.assign(currentDevice, clonedDevice);
							Systems.loadSystem(currentSystem);
							$state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
						}
						else {
							toastr.error(data.error);
						}
					}).
					error(toastr.error);
			};

			element.on('click', function(event) {
				// HOMESET-392 이슈 처리로 인해 모달창 동작 분기.
				if(scope.type == 'twoway_device'){
					scope.getTwowayVersion();
				}
				modal.$promise.then(modal.show);
			});

			scope.selectionsInitial = angular.copy(scope.selections);

			scope.cancelEdit = function() {
				scope.selections = angular.copy(scope.selectionsInitial);
			};




		}
	};
});



	

	

	


