'use strict';
define(function() {
  var gcelement = function(
    ogcFactory,
    gclayers,
    FeatureTypeFactory,
    SelectManager,
    $filter,
    gcInteractions,
    $timeout,
    gaJsUtils,
    PortalsFactory
  ) {
    return {
      templateUrl:
        'js/XG/widgets/utilities/select/views/gcselecteditclick.html',
      restrict: 'A',
      scope: {
        map: '=map',
        result: '=res',
        resgeometry: '=resgeometry',
        ftisid: '=ftisid',
        toolBarWidget: '=?toolbarwidget',
        onfinish: '&',
        field: '=?'
      },
      link: function(scope) {
        const map = scope.map;

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

        /**
         * toogleBtn
         */
        var toogleBtn = function() {
          if (
            scope._selectEditClickInteraction &&
            scope._selectEditClickInteraction.getActive() == true
          ) {
            scope._selectEditClickInteraction.setActive(false);
          }

          map.removeInteraction(scope._selectEditClickInteraction);
          gclayers.clearEditLayer();

          if (
            scope.isActive &&
            scope._selectEditClickInteraction &&
            scope._selectEditClickInteraction.getActive()
          ) {
            if (
              scope._selectEditClickInteraction &&
              angular.isDefined(scope._selectEditClickInteraction.getActive())
            )
              scope._selectEditClickInteraction.setActive(false);
            map.removeInteraction(scope._selectEditClickInteraction);
            scope.isActive = false;
          } else {
            if (
              scope._selectEditClickInteraction &&
              angular.isDefined(scope._selectEditClickInteraction.getActive())
            )
              scope._selectEditClickInteraction.setActive(true);
            scope.isActive = true;
          }
        };

        /**
         * selectAndEdit
         */
        scope.selectAndEdit = function() {
          toogleBtn();

          if (scope.isActive) {
            scope._selectEditClickInteraction = new ol.interaction.Draw({
              source: gclayers.getDrawLayer().getSource(),
              type: 'Point',
            });

            scope._selectEditClickInteraction.set('gctype', 'kis');
            scope._selectEditClickInteraction.set('interaction', 'Draw');
            scope._selectEditClickInteraction.set(
              'widget',
              'gcselecteditclick' + Math.random()
            );
            gcInteractions.setCurrentToolBar(scope.toolBarWidget);
            scope._selectEditClickInteraction.setActive(true);
            map.addInteraction(scope._selectEditClickInteraction);

            // on end
            scope._selectEditClickInteraction.on('drawend', function(evt) {
              gclayers.clearEditLayer();
              // URL de rcup des objets
              var types = '';

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

              if (types != '') {
                var format = new ol.format.GeoJSON(),
                  feature = format.writeFeatureObject(evt.feature),
                  x = feature.geometry.coordinates[0],
                  y = feature.geometry.coordinates[1],
                  view = map.getView(),
                  resolution =
                    view.getResolution() != 'undefined'
                      ? view.getResolution()
                      : 1,
                  leftX = x - 5 * resolution,
                  rightX = x + 5 * resolution,
                  bottomY = y - 5 * resolution,
                  topY = y + 5 * resolution;

                const cql_filter =  'INTERSECTS(geom, POLYGON((' +
                  leftX + ' ' + bottomY + ',' + rightX + ' ' + bottomY + ',' +
                  rightX + ' ' + topY + ',' + leftX + ' ' + topY + ',' +
                  leftX + ' ' + bottomY +
                  ')))';
                let useMode = 'query';
                if (scope.field
                  && scope.field.config.resgeometry && scope.field.config.resgeometry!=='') {
                  useMode = 'edition';
                }
                ogcFactory.getfeatures('GetFeature', 'WFS', '1.0.0', types, 'json',
                  map.getView().getProjection().getCode(), cql_filter, '',
                  undefined, undefined, useMode
                ).then((res) => {
                  if (res.data.totalFeatures != 0) {
                    var feature = new ol.format.GeoJSON().writeFeatureObject(
                      evt.feature
                    );
                    scope.resgeometry = feature.geometry;
                    // 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;
                    }
                    SelectManager.addFeaturesFromGeojson(scope.result);
                    $timeout(function() {
                      scope.onfinish();
                    });
                    scope.isActive = false;
                    scope._selectEditClickInteraction.setActive(false);
                    require('toastr').success(
                      $filter('translate')(
                        'layermanager.select_object_geometry'
                      )
                    );
                  } else {
                    scope.isActive = false;
                    scope._selectEditClickInteraction.setActive(false);
                    require('toastr').error(
                      $filter('translate')('layermanager.no_selectable_object')
                    );
                  }
                  gclayers.clearEditLayer();
                });
              } else {
                require('toastr').error(
                  $filter('translate')('layermanager.no_selectable_layer')
                );
              }
            });
          }
        };
      },
    };
  };

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