'use strict';
define(function() {
  var electroncondraw = function(
    $rootScope,
    $window,
    gcStyleFactory,
    gclayers,
    ogcFactory
  ) {
    return {
      templateUrl:
        'js/XG/widgets/mapapp/electroncondraw/views/electroncondraw.html',
      restrict: 'A',

      link: function(scope, element, attrs, ctrl) {
        $window.currentAction = null;
        scope.isActive = true;

        var format = new ol.format.GeoJSON();

        var map = scope.map;

        var troncon_hta_uid = '8a19e943-9fe8-476f-a2bd-3dc18725a970';

        var currAction = null;

        var translateInteraction;

        //style d'affichage des vertex
        var modifStyleFunction = function() {
          var regShape = new ol.style.RegularShape({
            points: 4,
            radius: 5,
            fill: new ol.style.Fill({ color: 'blue' }),
            stroke: new ol.style.Stroke({
              color: 'blue',
              width: 2,
            }),
          });

          return [
            new ol.style.Style({
              image: regShape,
              geometry: function(feature) {
                var coordinates = feature.getGeometry().getCoordinates()[0];
                return new ol.geom.MultiPoint(coordinates);
              },
            }),
            new ol.style.Style({
              stroke: new ol.style.Stroke({
                color: 'red',
                width: 2,
              }),
            }),
          ];
        };

        //initialisation du dragBox
        var dragBox = new ol.interaction.DragBox({
          condition: function(evt) {
            return evt.originalEvent.ctrlKey || scope.isActive;
          },

          style: gcStyleFactory.getStyle('selectrectangle'),
        });

        dragBox.set('gctype', 'kis');
        dragBox.set('interaction', 'Select');
        dragBox.set('widget', 'Edition');

        dragBox.on('boxend', function(evt) {
          //Recherche des objets intersectés par l'intersection
          var extent = dragBox.getGeometry().getExtent();
          var leftX = extent[0];
          var topY = extent[3];
          var rightX = extent[2];
          var bottomY = extent[1];
          var cql_filter =
            'INTERSECTS(geom, POLYGON((' +
            leftX +
            ' ' +
            bottomY +
            ',' +
            rightX +
            ' ' +
            bottomY +
            ',' +
            rightX +
            ' ' +
            topY +
            ',' +
            leftX +
            ' ' +
            topY +
            ',' +
            leftX +
            ' ' +
            bottomY +
            ')))';
          var promise = ogcFactory.getfeatures(
            'GetFeature',
            'WFS',
            '1.0.0',
            troncon_hta_uid,
            'json',
            map
              .getView()
              .getProjection()
              .getCode(),
            cql_filter
          );

          //Résultat de la sélection
          promise.then(
            function(res) {
              //Decodage de la featureCollection, (le decodage retourne un tableau de ol.feature)
              var selectedFeatures = format.readFeatures(res.data);

              //EditDescription: On ne prend en compte qu'un seul objet, le premier sélectionné.
              if (selectedFeatures.length > 0) {
                scope.editedfeature = selectedFeatures[0];

                if (currAction == 'editVertex') {
                  scope.editedfeature.setStyle(modifStyleFunction);

                  //Visualisation des features sélectionnés
                  gclayers
                    .getDrawLayer()
                    .getSource()
                    .addFeature(scope.editedfeature);

                  //Interaction de modification
                  if (scope.editedfeature != undefined) {
                    scope.fCollection = new ol.Collection();

                    scope.fCollection.push(scope.editedfeature);

                    scope.modifyInteraction = new ol.interaction.Modify({
                      features: scope.fCollection,
                      condition: function(event) {
                        console.log(
                          'event of ' +
                            event.type +
                            ' is dragging ' +
                            event.dragging
                        );
                        return true;
                      },
                      deleteCondition: function(event) {
                        return $window.currentAction == 'deleteVertex';
                      },
                      insertVertexCondition: function(event) {
                        return $window.currentAction == 'addVertex';
                      },
                      style: modifStyleFunction,
                    });

                    scope.modifyInteraction.set('gctype', 'kis');
                    scope.modifyInteraction.set('interaction', 'Modify');
                    scope.modifyInteraction.set('widget', 'Edition');

                    scope.modifyInteraction.setActive(false);

                    //Suppression de l'interaction de sélection
                    map.removeInteraction(dragBox);

                    //Ajout de l'interaction de modification à la map.
                    map.addInteraction(scope.modifyInteraction);

                    scope.modifyInteraction.setActive(true);

                    map.on('dblclick', onModifyEnd);
                  }
                } else if (currAction == 'deleteFeature') {
                  var styleSection = new ol.style.Style({
                    stroke: new ol.style.Stroke({
                      color: 'red',
                      width: 2,
                    }),
                  });

                  scope.editedfeature.setStyle(styleSection);

                  //Visualisation des features sélectionnés
                  gclayers
                    .getDrawLayer()
                    .getSource()
                    .addFeature(scope.editedfeature);

                  //Suppression de l'interaction de sélection
                  map.removeInteraction(dragBox);
                } else if (currAction == 'moveFeature') {
                  if (scope.editedfeature != undefined) {
                    var styleSection = new ol.style.Style({
                      stroke: new ol.style.Stroke({
                        color: 'red',
                        width: 2,
                      }),
                    });

                    scope.editedfeature.setStyle(styleSection);

                    //Visualisation des features sélectionnés
                    gclayers
                      .getDrawLayer()
                      .getSource()
                      .addFeature(scope.editedfeature);

                    var translateColl = new ol.Collection();

                    translateColl.push(scope.editedfeature);

                    translateInteraction = new ol.interaction.Translate({
                      features: translateColl,
                    });

                    //Suppression de l'interaction de sélection
                    map.removeInteraction(dragBox);

                    map.addInteraction(translateInteraction);
                  }
                }
              }
            },
            function(error) {
              console.error(
                'select feature() ogcFactory.getfeatures, error:' + error
              );
              require('toastr').error(error);
            }
          );
        });

        scope.editVertex = function() {
          currAction = 'editVertex';

          map.addInteraction(dragBox);
        };

        scope.hideVertex = function() {
          currAction = 'hideVertex';

          if (scope.modifyInteraction) {
            map.removeInteraction(scope.modifyInteraction);
          }

          gclayers
            .getDrawLayer()
            .getSource()
            .clear();
        };

        scope.deleteFeature = function() {
          currAction = 'deleteFeature';

          map.addInteraction(dragBox);
        };

        scope.moveFeature = function() {
          currAction = 'moveFeature';

          map.addInteraction(dragBox);
        };

        function onModifyEnd(clicEvent) {
          map.un('dblclick', onModifyEnd);

          if (scope.modifyInteraction)
            map.removeInteraction(scope.modifyInteraction);
        }
      },
    };
  };

  electroncondraw.$inject = [
    '$rootScope',
    '$window',
    'gcStyleFactory',
    'gclayers',
    'ogcFactory',
  ];
  return electroncondraw;
});
