'use strict';
define(function() {
  var urlsharing = function(
    $location,
    gclayers,
    SelectManager,
    $filter,
    $rootScope
  ) {
    return {
      templateUrl: 'js/XG/widgets/mapapp/urlsharing/views/urlsharing.html',

      restrict: 'AC',

      link: function(scope, elt, attrs, ctrl) {
        scope.url = {};

        scope.url_adress = $location.absUrl();

        /**
         *  if param is exist, replace the original part of url
         * @param param
         * @param value
         * @returns {boolean}
         */
        var remplaceParam = function(param, value) {
          if ($location.search()[param]) {
            var tableau_url = scope.url_adress.split('&');
            for (var i = 0; i < tableau_url.length; i++) {
              if (tableau_url[i].indexOf(param) == 0) {
                tableau_url[i] = param + '=' + value;
              }
            }
            scope.url_adress = tableau_url.join('&');
            return true;
          } else {
            return false;
          }
        };

        /**
         *  Create url sharing
         */
        scope.refresh = function() {
          scope.url_adress = $location.absUrl();

          if (scope.url.center) {
            var center =
              scope.map.getView().getCenter()[0] +
              ',' +
              scope.map.getView().getCenter()[1];

            if (!remplaceParam('center', center)) {
              scope.url_adress =
                scope.url_adress +
                '&center=' +
                scope.map.getView().getCenter()[0] +
                ',' +
                scope.map.getView().getCenter()[1];
            }
          }
          if (scope.url.zoom) {
            var zoom = scope.map.getView().getZoom();
            if (!remplaceParam('zoom', zoom)) {
              scope.url_adress =
                scope.url_adress + '&zoom=' + scope.map.getView().getZoom();
            }
          }
          if (scope.url.bbox) {
            var size = scope.map.getSize();
            var extent = scope.map.getView().calculateExtent(size);
            var bbox =
              extent[0] + ',' + extent[1] + ',' + extent[2] + ',' + extent[3];
            if (!remplaceParam('bbox', bbox)) {
              scope.url_adress =
                scope.url_adress +
                '&bbox=' +
                extent[0] +
                ',' +
                extent[1] +
                ',' +
                extent[2] +
                ',' +
                extent[3];
            }
          }

          /**
           *  if checkbox layers is true
           */
          if (scope.url.layers) {
            var fuids;
            var num = 0;
            gclayers.getOperationalLayerg2c().forEach(function(layer) {
              if (layer.getVisible()) {
                if (num == 0) {
                  fuids = layer.fti.uid;
                } else {
                  fuids = fuids + ',' + layer.fti.uid;
                }
                num++;
              }
            });

            if (fuids) {
              if (!remplaceParam('fuid', fuids)) {
                scope.url_adress = scope.url_adress + '&fuid=' + fuids;
              }
            }
          }

          /**
           *  if checkbox component selected is true
           */
          if (scope.url.features) {
            if (SelectManager.getfeatures().features) {
              var fids;
              var feature_ids = [];
              var featrue_names = [];
              SelectManager.getfeatures().features.forEach(function(feature) {
                feature_ids.push(feature.id);
                var o = feature.id.split('.');
                var contain = false;
                featrue_names.forEach(function(name) {
                  if (name == o[0]) {
                    contain = true;
                  }
                });
                if (contain == false) {
                  featrue_names.push(o[0]);
                }
              });
              feature_ids.sort(function(a, b) {
                return a.localeCompare(b);
              });
              featrue_names.sort(function(a, b) {
                return a.localeCompare(b);
              });

              var feature_names_copy = angular.copy(featrue_names);

              for (var i = 0; i < feature_names_copy.length; i++) {
                var first = true;
                for (var j = 0; j < feature_ids.length; j++) {
                  var id = feature_ids[j].split('.');
                  if (id[0] == feature_names_copy[i]) {
                    if (first) {
                      featrue_names[i] = featrue_names[i] + ':' + id[1];
                      first = false;
                    } else {
                      featrue_names[i] = featrue_names[i] + ',' + id[1];
                    }
                  }
                }
              }

              if (featrue_names.length) {
                fids = featrue_names.join(';');
              }

              if (fids) {
                if (!remplaceParam('fid', fids)) {
                  scope.url_adress = scope.url_adress + '&fid=' + fids;
                }
              }
            }
          }

          $rootScope.$broadcast('urlsharingchanged', scope.url_adress);
        };

        scope.$on('gcOperationalLayerChange', function(event, args) {
          scope.refresh();
        });

        /**
         *  Listen map changed
         */
        scope.map.getView().on('propertychange', function(e) {
          scope.refresh();
        });

        /**
         *  Listen features selected changed
         */
        scope.$on('gcSelectChange', function(event, args) {
          scope.refresh();
        });

        new Clipboard('.btn');
        scope.email = {
          title: 'KIS - Partage de lien',
        };

        scope.option = 'partager';
        scope.options = [
          {
            label: 'partager',
            name: $filter('translate')('urlsharing.options.share'),
          },
          {
            label: 'copier',
            name: $filter('translate')('urlsharing.options.copy'),
          },
        ];

        /**
         * toastr
         */
        scope.urlcopied = function() {
          require('toastr').info($filter('translate')('urlsharing.copied'));
        };
      },
    };
  };

  urlsharing.$inject = [
    '$location',
    'gclayers',
    'SelectManager',
    '$filter',
    '$rootScope',
  ];
  return urlsharing;
});
