'use strict';
define(function() {
  var gcelement = function(
    gclayers,
    gcStyleFactory,
    $http,
    FeatureTypeFactory,
    gcInteractions,
    SelectManager,
    $timeout,
    gaJsUtils,
    ogcFactory
  ) {
    return {
      templateUrl: 'js/XG/widgets/utilities/select/views/gcselectpolyg.html',
      restrict: 'A',
      scope: {
        map: '=map',
        result: '=res',
        geom: '=?geom',
        geomselect: '=?geomselect',
        ftisid: '=ftisid',
        toolBarWidget: '=?toolbarwidget',
        onfinish: '&',
        field: '=?',
        preventselect: '=?'
      },
      link: function(scope) {
        scope.ftis = [];
        scope.geom = '';

        scope.$watch('ftisid', function() {
          updateFtis();
        });
        function updateFtis() {
          scope.ftis.splice(0);
          // je prend chaque uid et je recupere le fti associe que j'injecte dans ftis
          for (var i in scope.ftisid) {
            scope.ftis.push(
              FeatureTypeFactory.getFeatureByUid(scope.ftisid[i])
            );
          }
        }
        updateFtis();

        scope.draw = new ol.interaction.Draw({
          type: 'Polygon',
        });

        scope.draw.set('gctype', 'kis');
        scope.draw.set('interaction', 'Draw');
        scope.draw.set('widget', 'gcselectpol' + Math.random());
        scope.draw.setActive(false);
        //Traitement de l'evenement de fin de dessin de sélection
        scope.draw.on('drawend', function(evt) {
          // URL de rcup des objets
          var types = '';

          // WFS a besoin des typesName (layer)
          scope.ftis.forEach(function(fType) {
            types = types + fType.uid + ',';
          });

          //Récupération de la géométrie dessinée
          var polygon = evt.feature.getGeometry();
          var multicoords = polygon.getCoordinates();
          scope.geom = evt.feature.getGeometry();
          var type = scope.geom.getType();
          let coords = scope.geom.getCoordinates();
          scope.geomselect = {
            coordinates: coords,
            type: type,
          };
          //Formatage de la geométrie et construction du filtre de recherche de features
          var polygonCoordsString = '';

          coords = multicoords[0];
          angular.forEach(coords, function(coord) {
            polygonCoordsString += coord[0] + ' ' + coord[1] + ',';
          });
          polygonCoordsString = polygonCoordsString.substring(
            0,
            polygonCoordsString.length - 1
          );

          const cql_filter = 'INTERSECTS(geom,POLYGON((' + polygonCoordsString + ')))';

          let useMode = 'query';
          if (scope.field && scope.field.config.geomselect && scope.field.config.geomselect!=='') {
            useMode = 'edition';
          }
          const promise = ogcFactory.getfeatures('GetFeature', 'WFS', '1.0.0', types, 'json',
            scope.map.getView().getProjection().getCode(), cql_filter, '',
            undefined, undefined, useMode
          );

          const promise2 = promise.then((res) => {
            if (!SelectManager.isGeojsonEmpty(res.data)) {
              // Dans le cas d'un formulaire d'intervention simple,
              // si on veut cumuler les sélections
              if(scope.field && scope.result && scope.field.config.cumulateSelections === true) {
                scope.result = gaJsUtils.mergeTwoGetFeatResult(res.data, scope.result);
              } else {
                scope.result = res.data;
              }

              if (!scope.preventselect) {
                SelectManager.addFeaturesFromGeojson(scope.result);
              }
              try {
                $timeout(()=>{
                  scope.$apply();
                });
              } catch(err) {}
            }
          });
          promise2.then(function() {
            scope.draw.setActive(false);
            scope.map.removeInteraction(scope.draw);
            scope.isActive = false;
            $timeout(function() {
              scope.onfinish()(evt);
            });
          });
        });

        scope.selectinterv = function() {
          var map = scope.map;
          scope.isActive = !scope.isActive;
          if (!scope.isActive) {
            scope.draw.setActive(false);
            map.removeInteraction(scope.draw);
            return;
          }
          gcInteractions.setCurrentToolBar(scope.toolBarWidget);
          scope.draw.setActive(true);
          map.addInteraction(scope.draw);
        };
      },
    };
  };

  gcelement.$inject = [
    'gclayers',
    'gcStyleFactory',
    '$http',
    'FeatureTypeFactory',
    'gcInteractions',
    'SelectManager',
    '$timeout',
    'gaJsUtils',
    'ogcFactory'
  ];
  return gcelement;
});
