var angular = require('angular');
var _ = require('jsUtil');
require('../modules');
var module = angular.module('flowmodulebase.directives');

module.factory('UnitService', function(LinkerService, $http) {
  return {
    get: function() {
      var url = '/archiveOfficeKey/getAll';
      return $http.get(url, {
        params: {
          userId: LinkerService.currentUserId
        },
        timeout: 15000
      }).then(function(response) {
        var units = [];
        var data = response.data;
        if (data) {
          for (var i = 0, len = data.length; i < len; i++) {
            units.push({
              value: data[i].id,
              text: data[i].name
            });
          }
        }
        return units;
      });
          }
      };
  });

module.directive('sinoUnitSelect', function($ionicModal, $q, UnitService) {
  return {
    restrict: 'AE',
    templateUrl: 'views/flowmodulebase/sinoUnitSelect.tpl.html',
    replace: true,
    require: '?ngModel',
    scope: {
      text: '='
    },
    bindToController: true,
    controllerAs: 'sinoUnitSelect',
    controller: function($scope, $attrs) {
      var ctrl = this,
        selectedItems = [],
        units = [],
        modal,
        modalScope;

      ctrl.openModal = function() {
        if ($attrs.readonly) {
          return;
        }
        if (modal) {
          modal.show();
        } else {
          createAndShowModal();
        }
      };

      UnitService.get().then(function(_units) {
        units = _units;
        generateSelectedItems(units);
        if (modalScope) {
          modalScope.items = units;
        }
      });

      function createAndShowModal() {
        if (modal) {
          modal.show();
          return modal;
        } else {
          var modalUrl = 'views/flowmodulebase/sinoUnitSelect.modal.tpl.html';
          modalScope = createModalScope();
          $ionicModal.fromTemplateUrl(modalUrl, {
            scope: modalScope,
            animation: 'slide-in-up',
            hardwareBackButtonClose: false
          }).then(function(_modal) {
            modal = _modal;
            modal.show();
          });
        }
      }

      function createModalScope() {
        var modalScope = $scope.$new();
        modalScope.selectItem = selectItem;
        modalScope.removeItem = removeItem;
        modalScope.clearSelectedItems = clearSelectedItems;
        modalScope.cancel = cancel;
        modalScope.selectedItems = selectedItems;
        modalScope.title = $attrs.modalTitle;
        modalScope.items = units;
        modalScope.confirm = confirm;
        return modalScope;
      }

      function selectItem(item) {
        for (var i = 0, len = selectedItems.length; i < len; i++) {
          if (selectedItems[i] === item) {
            selectedItems.splice(i, 1);
            return;
          }
        }
        selectedItems.push(item);
      }

      function removeItem(item) {
        for (var i = 0, len = selectedItems.length; i < len; i++) {
          if (selectedItems[i] === item) {
            delete selectedItems[i].$$selected;
            selectedItems.splice(i, 1);
            break;
          }
        }
      }

      function clearSelectedItems() {
        for (var i = 0, len = selectedItems.length; i < len; i++) {
          delete selectedItems[i].$$selected;
        }
        selectedItems.splice(0, selectedItems.length);
      }

      function cancel() {
        closeModal();
        generateSelectedItems(units);
      }

      function closeModal() {
        if (modal) {
          modal.hide();
          modal.remove();
          modalScope.$destroy();
          modalScope = null;
          modal = null;
        }
      }

      function confirm() {
        closeModal();
        setNgModelValue();
      }

      function setNgModelValue() {
        if (ctrl.ngModel) {
          ctrl.ngModel.$setViewValue(selectedItems.map(function(unit) {
            return unit.value;
          }).join(','));
        }
        ctrl.text = selectedItems.map(function(unit) {
          return unit.text;
        }).join(',');
      }

      function getConfigSelectedItemIds() {
        return ctrl.ngModel && ctrl.ngModel.$modelValue?
          ctrl.ngModel.$modelValue.split(',') : [];
      }

      function generateSelectedItems(units) {
        var unit;
        var selectedItemIds = getConfigSelectedItemIds();
        clearSelectedItems();
        for (var i = 0, len = units.length; i < len; i++) {
          unit = units[i];
          for (var j = 0, len2 = selectedItemIds.length; j < len2; j++) {
            if(selectedItemIds[j] == unit.value) {
              unit.$$selected = true;
              selectedItems.push(unit);
              break;
            }
          }
        }
      }

      $scope.$on('$destroy', closeModal);
    },
    link: function(scope, elements, attrs, ngModelCtrl) {
      scope.sinoUnitSelect.ngModel = ngModelCtrl;
    }
  };
});
