var angular = require('angular'),
  _ = require('jsUtil');

require('../modules');

angular
  .module('linker.services')
  .factory('UserChooser', UserChooser);

/** @ngInject */
function UserChooser($rootScope, $q, linkerConfig, $ionicModal) {

  var $scope = $rootScope.$new();

  return {
    choose: choose
  };

  function choose(scope, element, attrs) {
    $scope.filterFn = scope.filterFn;
    $scope.closeFn = scope.closeFn;

    var modalOpening = false,
      config = attrs.multiple;
    var multiple = attrs.hasOwnProperty('multiple') &&
      config !== 'false' && config != '0'

    openSelectUserModal();

    function createOpenUserTreeConfig() {
      var filterFn = attrs.filterFn? function(user, depts, superDepts) {
          return $scope.filterFn({
            user: user,
            depts: depts,
            superDepts: superDepts
          });
        } : function() {
          return true;
        };

      var config = {
        modalTitle: attrs.modalTitle,
        topDeptId: attrs.topDeptId || linkerConfig.topDeptId,
        type: 'user',
        moreSelect: multiple,
        selectType: {
          'user': true,
          'dept': false
        },'default': {
          'userIds':[]
        },
        filterFn: filterFn
      };
      return config;
    }

    function createModalScope() {
      var modalScope = $scope.$new();
      modalScope.treeConfig = createOpenUserTreeConfig();
      modalScope.close = function() {
        if (modalScope.modal) {
          modalScope.modal.hide();
          modalScope.modal.remove();
        }
        modalOpening = false;
      };

      $scope.closeTree = function(userIds) {
        $scope.closeFn({userIds: $scope.userId, userNames: $scope.userName});
        modalScope.close();
      };

      $scope.cancel = function() {
        modalScope.close();
      };

      modalScope.$on('$destroy', function() {
        modalScope.close();
      });

      modalScope.$on('selectNode', function(event, users) {
        var ids = [],
          names = [];

        for (var userId in users) {
          if (users.hasOwnProperty(userId)) {
            ids.push(userId);
            names.push(users[userId].userName);
          }
        }
        $scope.userName = names.join(',');
        $scope.userId = ids.join(',');
        event.stopPropagation();
      });

      return modalScope;
    }

    function openSelectUserModal() {
      if (attrs.readonly || modalOpening) {
        return;
      }
      modalOpening = true;
      var modalScope = createModalScope();
      $ionicModal.fromTemplateUrl('views/tree/modal/treeModuleZf.tpl.html', {
        scope: modalScope,
        animation: 'slide-in-up',
        hardwareBackButtonClose: true
      }).then(function(modal) {
        modalScope.modal = modal;
        modal.show();
      });
    };
  }


}
