'use strict';
define(function() {
  /**
   * @TODO SUPPRIME CAR REMPLACE PAR portalSwitcherAvance.js
   * Portal Switcher Directive
   * @param portalsFactory
   * @returns {{restrict: string, link: Function, templateUrl: string}}
   */
  var portalSwitcher = function($window, $rootScope, PortalsFactory, ngDialog) {
    return {
      restrict: 'EA',
      transclude: true,
      replace: true,
      link: function(scope) {

        /**
         * Set the current portal
         * @param portaluid
         */
        scope.setPortal = function(portaluid) {
          // find portal by uid
          var portal;
          PortalsFactory.resources.portals.forEach(function(p) {
            if (p.uid == portaluid) portal = p;
          });

          scope.selectedPortal = portal;
          PortalsFactory.setPortal(portal.uid);
          $window.location.reload();
        };

        function dynamicSort(property) {
          var sortOrder = 1;
          if (property[0] === '-') {
            sortOrder = -1;
            property = property.substr(1);
          }
          return function(a, b) {
            var result =
              a[property] < b[property]
                ? -1
                : a[property] > b[property]
                ? 1
                : 0;
            return result * sortOrder;
          };
        }

        scope.portalsList = [];
        scope.promptCreatePortal = false;

        var setDirectivePortal = function() {
          PortalsFactory.resources.portals.forEach(function(p) {
            if (scope.xgos.portal && p.uid == scope.xgos.portal.uid) {
              scope.selectedPortal = p;
            }
          });
        };

        scope.$watch(
          function() {
            return PortalsFactory.resources;
          },
          function(res) {
            if (typeof res !== 'undefined') {
              scope.portalsList = [];

              res.portals.forEach(function(p) {
                scope.portalsList.push({
                  text: p.name,
                  click: "setPortal('" + p.uid + "')",
                });
                setDirectivePortal();
              });
              scope.portalsList.sort(dynamicSort('text'));
              scope.promptCreatePortal = !scope.portalsList.length;
            }
          },
          1
        );

        scope.$watch(
          'xgos.portal',
          function(portal) {
            setDirectivePortal();
          },
          1
        );
      },
      templateUrl: 'js/XG/modules/portals/views/directives/portalSwitcher.html',
    };
  };

  portalSwitcher.$inject = [
    '$window',
    '$rootScope',
    'PortalsFactory',
    'ngDialog',
  ];
  return portalSwitcher;
});
