'use strict';
define(function() {
  var config = function($rootScope, gcWMS, FeatureTypeFactory, gclayers) {
    return {
      templateUrl: 'js/XG/modules/common/views/directives/features_config.html',
      scope: {
        config: '=',
        map: '=',
        tooltip: '=?', //tooltip on button
        fromAnc: '=?',
        baselayers: '=?',
      },
      restrict: 'EA',
      link: function(scope) {
        //console.log(scope.config)
        // console.log(scope.map)

        scope.mapFeatureConfig = {};
        scope.featuresObjectCompletEsri = [];
        scope.featuresObjectCompletG2c = [];
        scope.baseLayers = [];
        if (angular.isDefined(scope.config)) {
          // console.log(scope.config);
          var ind = 0;
          // we need to reset all layers to avoid multiple reverse (ticket 1548)
          gclayers.clearOperationalLayerg2c();
          Object.keys(scope.config).forEach(function(uid) {
            try {
              var f = FeatureTypeFactory.getFeatureByUid(uid);
              if (f.uid != "") {
                var l = gcWMS.getOlLayerFromFeaturetypeInfo(f, ind);
                if (gcWMS.getOlLayerFromFeaturetypeInfo(f) && f.type == 'esri') {
                  gclayers.addOperationalLayerESRI(l);
                  scope.featuresObjectCompletEsri.push(f);
                } else if (gcWMS.getOlLayerFromFeaturetypeInfo(f)) {
                  gclayers.addOperationalLayerg2c(l);
                  scope.featuresObjectCompletG2c.push(f);
                }
              } else {
                require('toastr').error("Couche configurée inexistante: " + uid +
                    ". Vous pouvez la supprimer de cette application.");
                console.error("Couche configurée inexistante: " + uid);
              }
            } catch (e) {
              e.stack;
            }
            ind++;
          });

          gclayers.getOperationalLayerg2cCollection().getArray().reverse();
          $rootScope.$broadcast('gcOperationalLayerOnInit');
          $rootScope.$broadcast('featuresConfigLoaded');
        }


        /**
         * refresh
         * @param index
         * @param f
         */
        scope.toggleVisibility = function (index, f) {
          if (scope.mapFeatureConfig[f.uid] === undefined) {
            scope.mapFeatureConfig[f.uid] = true;
          }
          scope.mapFeatureConfig[f.uid] = !scope.mapFeatureConfig[f.uid];

          var l = gcWMS.getOlLayerFromFeaturetypeInfo(f);
          gclayers.getOperationalLayerg2c().forEach(function (lay) {
            if (l.fti.uid == lay.fti.uid) {
              lay.setVisible(scope.mapFeatureConfig[f.uid]);
            }
          });
          gclayers.getOperationalLayerESRI().forEach(function (lay) {
            if (l.fti.uid == lay.fti.uid) {
              lay.setVisible(scope.mapFeatureConfig[f.uid]);
            }
          });
          $rootScope.$broadcast('gcOperationalLayerChange', '', 'applyall');
        };

        /**
         * toggleBaseMap
         */
        scope.toggleBaseMap = (layer) => {
            layer.active = !layer.active;
            toggleBaseLayer(layer);
        };
        function toggleBaseLayer(layer) {
          const bgLayers = gclayers.getBackGroundLayer();
          bgLayers.forEach(x => {
            x.setVisible(false);
          })
          const bgLayer = bgLayers.filter((bg) => bg.name == layer.name)[0];
          bgLayer.setVisible(layer.active);
        }
      

        if (angular.isDefined(scope.fromAnc) && scope.fromAnc) {
          if (scope.config.baselayers) {
            delete scope.config.baselayers;
          }
          Object.keys(scope.config).forEach(function (couche, i) {
            if (
              angular.isDefined(scope.config[couche]) &&
              angular.isDefined(scope.config[couche].split('-', 2)[1])
            ) {
              var f = FeatureTypeFactory.getFeatureByUid(couche);
              if (scope.config[couche].split('-', 2)[1] == '0' && f != null)
                scope.toggleVisibility(i, f);
            }
          });
        }

        scope.moveItem = function (index, delta, type) {
          if (type == 'esri') {
            var layer = gclayers.getOperationalLayerESRI()[index];
            gclayers.getOperationalLayerESRICollection().removeAt(index);
            gclayers
              .getOperationalLayerESRICollection()
              .insertAt(index + delta, layer);
            layer.index = index + delta;
            swapItems(scope.featuresObjectCompletEsri, index, index + delta);
          } else {
            gclayers.getOperationalLayerg2cCollection().getArray().reverse();
            var layer = gclayers.getOperationalLayerg2c()[index];
            gclayers.getOperationalLayerg2cCollection().removeAt(index);
            gclayers
              .getOperationalLayerg2cCollection()
              .insertAt(index + delta, layer);
            layer.index = index + delta;
            swapItems(scope.featuresObjectCompletG2c, index, index + delta);
            gclayers.getOperationalLayerg2cCollection().getArray().reverse();
          }
          $rootScope.$broadcast('gcOperationalLayerChange', '', 'applyall');
        };

        var swapItems = function (arr, index1, index2) {
          arr[index1] = arr.splice(index2, 1, arr[index1])[0];
          return arr;
        };
      },
    };
  };

  config.$inject = ['$rootScope', 'gcWMS', 'FeatureTypeFactory', 'gclayers'];
  return config;
});
