'use strict';
define(function() {
  var gcelement = function(
    $http,
    gclayers,
    gcStyleFactory,
    FeatureTypeFactory,
    GeometryFactory,
    gcInteractions,
    gaJsUtils, ogcFactory
  ) {
    return {
      templateUrl:
        'js/XG/widgets/utilities/select/views/gcselectandbufferise.html',

      restrict: 'A',
      scope: {
        map: '=map',
        result: '=res',
        resbuffer: '=resbuffer',
        geomselection: '=?geomselection',
        updateselection: '=?updateselection',
        ftisid: '=ftisid',
        typebuffer: '=typebuffer',
        distance: '=distance',
        toolBarWidget: '=?toolbarwidget',
        onfinish: '&',
        field: '=?',
        // -- Indique s'il faut alimenter rebuffer ou non
        // -- Il faut l'alimenter quand resbuffer a été configuré
        // -- S'il ne l'est pas le résultat sera mis dans
        // -- res[field.config.resbuffer].geometry soit dans res.undefined.geometry,
        // -- or si field.config.updateselection n'est pas défini lui non plus
        // -- updateselection sera mis dans res.undefined et donc le watch
        // -- sur updateselection indûment utilisé d'une part et avec bouclage infini d'autre part
        withresbuffer: '=withresbuffer'
      },
      link: function(scope) {

        scope.intervFeature = {};
        //console.log ("TEST FF ");

        scope.ftis = [];
        for (var i in scope.ftisid) {
          //     console.log(scope.ftisid[i]);
          scope.ftis.push(FeatureTypeFactory.getFeatureByUid(scope.ftisid[i]));
        }

        //console.log(scope.ftis);

        scope.generatebuffer = function(data) {
          console.log(data);

          if (scope.intervFeature == {}) {
            scope.intervFeature = scope.templatefeat;
          }

          if (!angular.isDefined(data.features)) return;
          gclayers.clearEditLayer();

          if (data.features.length == 0) {
            scope.resbuffer = '';
          } else {
            var geom = [];
            if (data.features.geometry) {
              geom.push(data.features.geometry);
            }
            else {
              data.features.forEach(function(f) {
                geom.push(f.geometry);
              });
            }
            GeometryFactory.unionandbuffer(
              geom,
              scope.typebuffer,
              scope.distance
            ).then(function(res) {
              scope.intervFeature.geometry = res.data;
              scope.intervFeature.type = 'Feature';
              scope.intervFeature.properties = {};
              if (scope.withresbuffer) {
                scope.resbuffer = res.data;
              }

              var vector_source = gclayers.getDrawLayer().getSource();
              var parser = new ol.format.GeoJSON();
              vector_source.addFeature(parser.readFeature(scope.intervFeature));

              scope.onfinish();
            });
          }
        };

        // template geojson
        scope.templatefeat = {
          type: 'Feature',
          id: 'newid',
          geometry: {},
          geometry_name: 'geom',
          properties: {},
        };
        scope.altKeyPressed = false;
        // selection et gestion des evenements
        scope.selectinterv = function() {
          var map = scope.map;
          scope.isActive = true;
          scope.dragBox = new ol.interaction.DragBox({
            condition: function(evt) {
              console.log(evt.originalEvent.altkey);
              scope.altKeyPressed = evt.originalEvent.ctrlKey;
              //MacEnvironments don't get here because the event is not
              //recognized as mouseEvent on Mac by the google closure.
              //We have to use the apple key on those devices
              return (
                evt.originalEvent.ctrlKey || scope.isActive
              ); /* ||
                             (gaBrowserSniffer.mac && evt.originalEvent.metaKey);*/
            },
            style: gcStyleFactory.getStyle('selectrectangle'),
          });

          scope.dragBox.set('gctype', 'kis');
          scope.dragBox.set('interaction', 'Select');
          scope.dragBox.set('widget', 'gcselectbufferise');
          gcInteractions.setCurrentToolBar(scope.toolBarWidget);
          scope.dragBox.setActive(true);
          map.addInteraction(scope.dragBox);

          scope.dragBox.on('boxend', function() {
            // URL de rcup des objets
            let res = '';

            // WFS a besoin des typesName (layer)
            scope.ftis.forEach(function(fType) {
              res = res + fType.uid + ',';
            });
            // var filter = gclayers.getSelectFilterasStringuid(map);
            const geometryExtent = scope.dragBox.getGeometry().getExtent();
            scope.geomselection = scope.dragBox.getGeometry();
            const leftX = geometryExtent[0];
            const bottomY = geometryExtent[1];

            const rightX = geometryExtent[2];
            const topY = geometryExtent[3];
            const cql_filter='INTERSECTS(geom, POLYGON((' +
              leftX + ' ' +bottomY +',' +rightX +' ' +bottomY +',' +
              rightX +' ' +topY + ',' + leftX + ' ' + topY + ',' +
              leftX + ' ' + bottomY + ')))';
            let useMode = 'query';
            if (scope.field.config.resbuffer && scope.field.config.resbuffer!=='') {
              useMode = 'edition';
            }
            ogcFactory.getfeatures( 'GetFeature', 'WFS', '1.0.0', res, 'json',
              map.getView().getProjection().getCode(),
              cql_filter, undefined, undefined, undefined, useMode
            ).then((res) => {
              if (scope.altKeyPressed) {
                var feats = scope.result;
                if (angular.isUndefined(feats.length)) {
                  feats = scope.result.features;
                }
                for (var i = 0; i < feats.length; i++) {
                  res.data.features.push(feats[i]);
                }
                res.data.totalFeatures = res.data.features.length;
              }

              // 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;
              }

              scope.generatebuffer(scope.result);
            });

            // updateselection was modified
            scope.$watch(
              'updateselection',
              (updateselection) => {
                if (angular.isDefined(updateselection) && updateselection.geometry!=='') {
                  if (
                    updateselection.constructor === Object &&
                    Object.keys(updateselection).length === 0
                  ) {
                    return;
                  }
                  if (
                    updateselection.hasOwnProperty('type') &&
                    updateselection.type == 'FeatureCollection'
                  ) {
                    return;
                  }

                  var featureCollection = {};
                  featureCollection.type = 'FeatureCollection';
                  featureCollection.features = updateselection;
                  scope.generatebuffer(featureCollection);
                }
              },
              1
            );
            scope.dragBox.setActive(false);
            map.removeInteraction(scope.dragBox);
          });
        };
      },
    };
  };

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