'use strict';
//dependent upon on Bootstrap

app.directive('activityDeviceSelect', function () {
  return {
    restrict: 'E',
    require: 'ngModel',
    replace: true,
    scope: {
      ngModel: '=',
      roomDevices: '=',
      powerInputMode: '=', //default: false (power off), true (power on, input)
      disable: '=' //if true, hides the list 
    },
    templateUrl: 'views/activity-device-select.html',
    link: function(scope, element, attrs) {
      scope.powerInputMode = scope.powerInputMode || false;
    },
    controller: function($scope, $modal) {
      $scope.showPopup = true;

      // input 에 체크가 해제되면 navigation 체크 해제시킴
      $scope.$watch('ngModel', function(newVal, oldVal) {
        var checkedInputs = [];

        _.each(newVal, function(item) {
          if (item.type === 2) {
            checkedInputs.push(item.device_id);

            if (item.navigate) {
              if (angular.element('#navigation' + item.device_id)[0]) {
                angular.element('#navigation' + item.device_id)[0].checked = true;
              }
            }
          }
        });

        angular.element('input.navigation').each(function() {
          var self = this,
            deviceId = +(self.id.split('navigation')[1]);

          if (checkedInputs.indexOf(deviceId) === -1) {
            self.checked = false;
          }
        });
      }, true);

      $scope.checked = function(deviceId) {
        var input = _.find($scope.ngModel, function(item) {
          return item.type === 2 && item.device_id === deviceId;
        });

        if (!input || !input.navigate) {
          return null;
        } else {
          return true;
        }
      };

      // navigation 체크할 때
      $scope.checkNavigation = function(deviceId) {
        var input = _.find($scope.ngModel, function(item) {
          return item.type === 2 && item.device_id === deviceId;
        });

        if (!input) {
          angular.element('#navigation' + deviceId)[0].checked = false;
        }

        if (angular.element('#navigation' + deviceId)[0].checked) {
          input.navigate = 1;

          if ($scope.showPopup) {
            var modal = $modal({
              scope: $scope,
              template: 'views/modal-tpls/navigating-television.html',
              container: 'body',
              show: false
            });
            modal.$promise.then(modal.show);
          }
        } else {
          if (input && input.navigate) {
            delete input.navigate;
          }
        }
      };

      $scope.hidePopup = function() {
        $scope.showPopup = false;
      };
    }
  };
});
