'use strict';
/**
 * @ngdoc controller
 * @name AdvancedDeviceTypeController
 * @description
 *  device type 선택
 */
app.controller('AdvancedDeviceTypeController', function ($rootScope, $scope, $state, toastr, categories, Systems) {
  var currentSystem = Systems.getCurrentSystem(),
    twowayDevicesCount = 0;

  $scope.twowayDevicesLimit = $rootScope.env.twowayDevicesLimit;

  $scope.allowTwowayDevices = true;
  _.each(currentSystem.rooms, function(room) {
    twowayDevicesCount += room.twoway_devices.length || 0;
  });

  // Advanced Device 는 최대 $scope.twowayDevicesLimit 개까지만 추가할 수 있음
  if (twowayDevicesCount >= $scope.twowayDevicesLimit) {
    $scope.allowTwowayDevices = false;
    toastr.error('There are already ' + $scope.twowayDevicesLimit + ' Advanced Devices in the system.  You must delete one of them before adding another. Go to the Home Overview to delete devices.');
  }

  if (!$scope.device.type) {
    $scope.device.type = {id: categories[0].id, name: categories[0].name, target_type: categories[0].target_type};  // 기본값 설정

    //브랜드 네임이 있으면 추가 한다.
    if(categories[0].brand_name){
      $scope.device.type.brand_name = categories[0].brand_name;
    }

    if (categories[0].variables && categories[0].variables.length) {
      $scope.device.type.variables = categories[0].variables;
    }
  }

  $scope.types = categories;

  // 콤보박스 선택시에 브랜드 네임과 디바이스 네임을 반환한다.
  $scope.getCombolabel = function(item){
    if(item.brand_name){
      return item.name === 'TRF-ZW1' ? item.brand_name + ' ' + 'TRF-ZW' : (item.brand_name === item.name ? item.name : item.brand_name + ' ' + item.name);
    } else {
      return item.name;
    }
  }

  // advanced device type 을 선택할 때 More... 가 나올지 여부 설정
  if ($rootScope.env.advancedDeviceMore) {
    if (!_.findWhere($scope.types, { name: 'More...' })) {
      $scope.types.push({
        name: 'More...'
      });
    }

    // More... 를 선택한 경우 선택가능한 device type 을 Systems.getTwowayCategories 를 통해 다시 불러옴
    $scope.$watch('device.type', function(newVal, oldVal) {
      if (newVal.name === 'More...') {
        $state.go('menu.programming.add-advanced-device.more-device-category');
      }
    });
  }

  $scope.doNext = function () {
    // System에 걸쳐 TRF-ZW1은 한개
    // 이미 등록된 TRF-ZW1 이 있으면 진행하지 않음
    var trfzw1Exist = false;

    _.each(currentSystem.rooms, function(room) {
      _.each(room.twoway_devices, function(twoway_device) {
        if (twoway_device.model === 'TRF-ZW1') {
          trfzw1Exist = true;
        }
      });
    });

    if (trfzw1Exist && $scope.device.type.name === 'TRF-ZW1') {  // system 에 TRF-ZW1 이 존재하는데 TRF-ZW1 을 추가하려고 선택한 경우
      toastr.error('There is already a TRF-ZW in the system.');
    } else {
      if ($scope.device.type.variables && $scope.device.type.variables.length) {
        $scope.device.model = angular.copy($scope.device.type);
        $state.go('menu.programming.add-advanced-device.more-device-name');
      } else {
        $state.go('menu.programming.add-advanced-device.device-name');
      }
    }
  };
});

/**
 * @ngdoc controller
 * @name MoreAdvancedDeviceCategoryController
 * @description
 *  more device category 선택
 */
app.controller('MoreAdvancedDeviceCategoryController', function ($scope, $state, toastr, moreCategories, Systems) {
  delete($scope.device.type);

  var currentSystem = Systems.getCurrentSystem();

  if (!$scope.device.category) {
    $scope.device.category = {id: moreCategories[0].id, name: moreCategories[0].name};  // 기본값 설정
  }
  $scope.categories = moreCategories;

  $scope.$watch('device.category', function(newVal, oldVal) {
    if (newVal && oldVal && newVal.id !== oldVal.id) {
      $scope.device.brand = null;
      $scope.device.model = null;
    }
  });

  $scope.doNext = function () {
    // System에 걸쳐 TRF-ZW1은 한개
    // 이미 등록된 TRF-ZW1 이 있으면 진행하지 않음
    var trfzw1Exist = false;

    _.each(currentSystem.rooms, function(room) {
      _.each(room.twoway_devices, function(twoway_device) {
        if (twoway_device.model === 'TRF-ZW1') {
          trfzw1Exist = true;
        }
      });
    });

    if (trfzw1Exist && $scope.device.category.name === 'TRF-ZW1') {  // system 에 TRF-ZW1 이 존재하는데 TRF-ZW1 을 추가하려고 선택한 경우
      toastr.error('There is already a TRF-ZW in the system.');
    } else {
      $state.go('menu.programming.add-advanced-device.more-device-name');
    }
  };
});

/**
 * @ngdoc controller
 * @name AdvancedDeviceNameController
 * @description
 *  device name 입력
 */
app.controller('AdvancedDeviceNameController', function ($scope, $state, $modal, toastr, Database, Rooms, Devices, Systems) {
  $scope.device.name = $scope.device.type.name === 'TRF-ZW1' ? 'TRF-ZW' : angular.copy($scope.device.type.name);

  // MAC
  if ($scope.device.type.target_type & 0x0001) {
    // discovery
    if ($scope.device.type.target_type & 0x00010000) {
      $scope.device.addType = 'discovery';
    }
    // mac
    else {
      $scope.device.addType = 'mac';
    }
  } else {
    // IP
    if ($scope.device.type.target_type & 0x0002) {
      $scope.device.addType = 'ip';
    }
    // service
    else if ($scope.device.type.target_type & 0x0004) {
      $scope.device.addType = 'service';
    }
  }

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

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

  $scope.doNext2 = function() {
    if ($scope.device.addType === 'service') {
      $state.go('menu.programming.add-advanced-device.device-review', {'addType': 'service'});
    } else {
      $state.go('menu.programming.add-advanced-device.device-identification', {'addType': $scope.device.addType, 'model': $scope.device.type.name});
    }
  };
});

/**
 * @ngdoc controller
 * @name MoreAdvancedDeviceNameController
 * @description
 *  more device name 입력
 */
app.controller('MoreAdvancedDeviceNameController', function ($scope, $state, $modal, toastr, Database, Rooms, Devices, Systems) {
  // 같은 이름의 device name 이 이미 등록되어 있음을 알리는 modal
  var modal = $modal({
    scope: $scope,
    title: 'Duplicate device name',
    container: '.editor-container',
    template: 'views/modal-tpls/twoway-duplicate-name.html',
    show: false
  });

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

  $scope.doNext2 = function() {
    if ($scope.device.category && $scope.device.category.id) {
      $state.go('menu.programming.add-advanced-device.more-device-brand', {'categoryId': $scope.device.category.id});
    } else {
      // variables 입력 - mac, ip 도 입력해야 할 수 있음
      if ($scope.device.model.variables && $scope.device.model.variables.length) {
        $scope.device.addType = 'variables';
        $state.go('menu.programming.add-advanced-device.more-device-identification');
      }
      // mac 입력
      else if ($scope.device.model.target_type === 1) {
        $scope.device.addType = 'mac';
        $state.go('menu.programming.add-advanced-device.more-device-identification');
      }
      // IP 입력
      else if ($scope.device.model.target_type === 2) {
        $scope.device.addType = 'ip';
        $state.go('menu.programming.add-advanced-device.more-device-identification');
      }
      // device review 화면으로 이동
      else {
        $state.go('menu.programming.add-advanced-device.more-device-review');
      }
    }
  };
});

/**
 * @ngdoc controller
 * @name MoreAdvancedDeviceBrandController
 * @description
 *  more device brand 선택
 */
app.controller('MoreAdvancedDeviceBrandController', function ($scope, $state, $modal, toastr, brands) {
  $scope.brands = brands;

  $scope.$watch('device.brand', function(newVal, oldVal) {
    if (newVal && oldVal && newVal.id !== oldVal.id) {
      $scope.device.model = null;
    }
  });

  $scope.doNext = function() {
    $state.go('menu.programming.add-advanced-device.more-device-model', {'brandId': $scope.device.brand.id});
  };
});

/**
 * @ngdoc controller
 * @name MoreAdvancedDeviceModelController
 * @description
 *  more device model 선택
 */
app.controller('MoreAdvancedDeviceModelController', function ($scope, $state, $modal, toastr, models) {
  $scope.models = models;

  $scope.doNext = function() {
    // variables 입력 - mac, ip 도 입력해야 할 수 있음
    if ($scope.device.model.variables && $scope.device.model.variables.length) {
      $scope.device.addType = 'variables';
      $state.go('menu.programming.add-advanced-device.more-device-identification');
    }
    // mac 입력
    else if ($scope.device.model.target_type === 1) {
      $scope.device.addType = 'mac';
      $state.go('menu.programming.add-advanced-device.more-device-identification');
    }
    // IP 입력
    else if ($scope.device.model.target_type === 2) {
      $scope.device.addType = 'ip';
      $state.go('menu.programming.add-advanced-device.more-device-identification');
    }
    // device review 화면으로 이동
    else {
      $state.go('menu.programming.add-advanced-device.more-device-review');
    }
  };
});

/**
 * @ngdoc controller
 * @name MoreAdvancedDeviceReviewController
 * @description
 *  more device review
 */
app.controller('MoreAdvancedDeviceReviewController', function ($scope, $state, $modal, toastr, Devices, Systems) {
  var d = {
      name: $scope.device.name,
      model: $scope.device.model.name,
      modelId: $scope.device.model.id,
      targetType: $scope.device.model.target_type,
      targetAddr: '""',
      variables: '""'
    },
    jsonData;

  // mac
  if ($scope.device.addType === 'mac') {
    d.targetAddr = $scope.device.key.mac1 + $scope.device.key.mac2 + $scope.device.key.mac3 + $scope.device.key.mac4 + $scope.device.key.mac5 + $scope.device.key.mac6;
    d.targetAddr = d.targetAddr.toUpperCase();
  }
  // IP
  else if ($scope.device.addType === 'ip') {
    d.targetAddr = $scope.device.ip.address + ':' + $scope.device.ip.port;
  }
  // variables
  else if ($scope.device.addType === 'variables') {
    if ($scope.device.model.target_type === 1) {
      d.targetAddr = $scope.device.key.mac1 + $scope.device.key.mac2 + $scope.device.key.mac3 + $scope.device.key.mac4 + $scope.device.key.mac5 + $scope.device.key.mac6;
    } else if ($scope.device.model.target_type === 2) {
      d.targetAddr = $scope.device.ip.address + ':' + $scope.device.ip.port;
    }

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

      d.variables.push(obj);
    });
  }

  jsonData = JSON.stringify(d);

  // device 생성
  $scope.doNext = function() {
    return Devices.createTwowayDevice($scope.room.id, jsonData)
      .then(function(data) {
        console.log(data);

        Systems.updateSystem(Systems.getCurrentSystem().id).then(function() {
          $state.transitionTo('menu.programming.options', null, { reload: true, inherit: true, notify: true  });
        }).catch(function(error) {
          toastr.error(error);
        });
      })
      .catch(toastr.error);
  };
});

/**
 * @ngdoc controller
 * @name MoreAdvancedDeviceIdentificationController
 * @description
 *  more device 정보 설정
 */
app.controller('MoreAdvancedDeviceIdentificationController', function ($scope, $state, $modal, toastr, Database, Rooms, Devices, Systems) {
  if (typeof $scope.device.key === 'undefined') {
    $scope.device.key = {};
  }
  if (typeof $scope.device.ip === 'undefined') {
    $scope.device.ip = {};
  }

  // mac or IP
  if ($scope.device.addType === 'mac' || $scope.device.addType === 'ip') {
    $scope.doNext = function() {
      $state.go('menu.programming.add-advanced-device.more-device-review');
    };
  }
  // variables
  else if ($scope.device.addType === 'variables') {
    $scope.device.varData = {};
    $scope.device.varUsername = false;
    $scope.device.varPassword = false;
    $scope.device.varPort = false;
    $scope.device.variables = [];

    _.each($scope.device.model.variables, function(item) {
      if (item.name === 'username') {
        $scope.device.varUsername = true;
      }
      if (item.name === 'password') {
        $scope.device.varPassword = true;
      }
      if (item.name === 'device_port') {
        $scope.device.varPort = true;

        if (item['default']) {
          $scope.device.ip.port = +item['default'];
        }
      }

      $scope.device.varData[item.name] = item;
      if (item['default']) {
        $scope.device.varData[item.name].value = item['default'];
      }

      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;
      }

      $scope.device.variables.push(item);
    });

    var upRestLength = $scope.device.varPort ? 3 : 2;   // device_port 가 있는 경우에는 username, password, device_port 까지 3개를 빼고 계산해야 함

    // username/password 가 있는지, 나머지 variables 가 있는지 여부에 따라 페이지 구성이 달라짐
    // 1. username/password 가 있으면서 나머지 variables 도 있는 경우
    if ($scope.device.varUsername && $scope.device.varPassword && $scope.device.variables.length > upRestLength) {
      $scope.device.varType = 'UPV';    // username, password, others
    }
    // 2. username/password 만 있는 경우
    else if ($scope.device.varUsername && $scope.device.varPassword && $scope.device.variables.length === upRestLength) {
      $scope.device.varType = 'UP';     // username, password
    }
    // 3. username/password 가 없으면서 나머지 variables 가 있는 경우
    else if (($scope.device.varPort && $scope.device.variables.length > 1) || (!$scope.device.varPort && $scope.device.variables.length > 0)) {
      $scope.device.varType = 'V';      // 나머지 variables
    }
    // 4. IP/Port 입력만 필요한 경우
    else if ($scope.device.varPort && $scope.device.variables.length === 1) {
      $scope.device.varType = 'IP';
    }

    // mac/ip 입력하는 화면, username/password 입력하는 화면, 나머지 variables 입력하는 화면
    if ($scope.device.model.target_type === 1 || $scope.device.model.target_type === 2) {
      $scope.device.varStep = 'mac_ip';
    } else if ($scope.device.varType === 'UPV' || $scope.device.varType === 'UP') {
      $scope.device.varStep = 'UP';
    } else {
      $scope.device.varStep = 'V';
    }

    $scope.doNext = function() {
      if ($scope.device.varStep === 'mac_ip') {
        if ($scope.device.varUsername && $scope.device.varPassword) {
          $scope.device.varStep = 'UP';
        } else if ($scope.device.varType === 'IP') {
          // review 페이지로 이동
            // json data 생성
            $scope.device.allVariables = [];

            _.each($scope.device.variables, function(item) {
              $scope.device.allVariables.push(item);
            });

            $state.go('menu.programming.add-advanced-device.more-device-review');
        } else {
          $scope.device.varStep = 'V';
        }
      }
      else if ($scope.device.varStep === 'UP' && $scope.device.varType === 'UPV') {
        $scope.device.varStep = 'V';
      }
      // review 페이지로 이동
      else {
        // json data 생성
        $scope.device.allVariables = [];

        _.each($scope.device.variables, function(item) {
          $scope.device.allVariables.push(item);
        });

        $state.go('menu.programming.add-advanced-device.more-device-review');
      }
    };
  }
});

/**
 * @ngdoc controller
 * @name AdvancedDeviceIdentificationController
 * @description
 *  device 추가
 */
app.controller('AdvancedDeviceIdentificationController', function ($rootScope, $scope, $state, $modal, toastr, devices, Database, Rooms, Devices, Systems) {
  $scope.trfZwLink = $rootScope.env.trfZwLink;

  if ($scope.device.addType === 'discovery') {
    $scope.twowayDevices = devices.searchedDevices || [];
  }

  $scope.device.key = {};
  $scope.device.ip = {};

  // discovery
  if ($scope.device.addType === 'discovery') {
    $scope.$watch('device.mac', function() {
      $scope.device.targetAddr = $scope.device.mac;
    });
  }
  // mac
  else if ($scope.device.addType === 'mac') {
    $scope.$watch('device.key', function() {
      $scope.device.targetAddr = $scope.device.key.mac1 + $scope.device.key.mac2 + $scope.device.key.mac3 + $scope.device.key.mac4 + $scope.device.key.mac5 + $scope.device.key.mac6;
      $scope.device.targetAddr = $scope.device.targetAddr.toUpperCase();
    }, true);
  }
  // IP
  else if ($scope.device.addType === 'ip') {
    $scope.$watch('device.ip', function() {
      $scope.device.targetAddr = $scope.device.ip.address + ':' + $scope.device.ip.port;
    }, true);
  }

  $scope.doNext = function() {
    if ($scope.device.addType === 'mac') {
      $state.go('menu.programming.add-advanced-device.device-review', {'addType': 'mac'});
    } else {
      var d = {
          name: $scope.device.name,
          model: $scope.device.type.name,
          modelId: $scope.device.type.id,
          targetType: $scope.device.type.target_type,
          targetAddr: $scope.device.targetAddr,
          variables: '""'
        },
        jsonData = JSON.stringify(d);

      // device 생성
      return Devices.createTwowayDevice($scope.room.id, jsonData)
        .then(function(data) {
          console.log(data);

          Systems.updateSystem(Systems.getCurrentSystem().id).then(function() {
            if ($scope.trfZwLink && $scope.device.type.name === 'TRF-ZW1') {
              $state.go('menu.programming.add-advanced-device.trf-zw-setup');
            } else {
              $state.transitionTo('menu.programming.options', null, { reload: true, inherit: true, notify: true  });
            }
          }).catch(function(error) {
            toastr.error(error);
          });
        })
        .catch(toastr.error);
    }
  };

  $scope.getTwowayDevices = function(type) {
    Systems.getTwowayDevices(type).then(
      function(data) {
        $scope.twowayDevices = data.searchedDevices || [];
      },
      function(error) {
        toastr.error(error, 'Error');
      }
    );
  };
});

/**
 * @ngdoc controller
 * @name AdvancedDeviceReviewController
 * @description
 *  device review
 */
app.controller('AdvancedDeviceReviewController', function ($scope, $state, $stateParams, $modal, toastr, Devices, Systems) {
  var d, jsonData;

  $scope.doNext = function() {
    if ($stateParams.addType === 'service') {
      d = {
        name: $scope.device.name,
        model: $scope.device.type.name,
        modelId: $scope.device.type.id,
        targetType: $scope.device.type.target_type,
        targetAddr: '""',
        variables: '""'
      };
      jsonData = JSON.stringify(d);

      // device 생성
      return Devices.createTwowayDevice($scope.room.id, jsonData)
        .then(function(data) {
          console.log(data);

          Systems.updateSystem(Systems.getCurrentSystem().id).then(function() {
            $state.transitionTo('menu.programming.options', null, { reload: true, inherit: true, notify: true  });
          }).catch(function(error) {
            toastr.error(error);
          });
        })
        .catch(toastr.error);
    } else if ($stateParams.addType === 'mac') {
      d = {
        name: $scope.device.name,
        model: $scope.device.type.name,
        modelId: $scope.device.type.id,
        targetType: $scope.device.type.target_type,
        targetAddr: $scope.device.targetAddr,
        variables: '""'
      };
      jsonData = JSON.stringify(d);

      // device 생성
      return Devices.createTwowayDevice($scope.room.id, jsonData)
        .then(function(data) {
          console.log(data);

          Systems.updateSystem(Systems.getCurrentSystem().id).then(function() {
            $state.transitionTo('menu.programming.options', null, { reload: true, inherit: true, notify: true  });
          }).catch(function(error) {
            toastr.error(error);
          });
        })
        .catch(toastr.error);
    }
  };
});

/**
 * @ngdoc controller
 * @name AdvancedDeviceTrfZwSetupController
 * @description
 *  TRF-ZW setup 안내 페이지
 */
app.controller('AdvancedDeviceTrfZwSetupController', function ($rootScope, $scope, $state) {
  $scope.urcControlRoomLink = $rootScope.env.urcControlRoomLink;
  $scope.urcControlRoomUrl = $rootScope.env.urcControlRoomUrl;

  $scope.finish = function() {
    $state.go('menu.programming.options');
  };
});