'use strict';
define(function() {
  var filterMap = function(
    ngDialog,
    $rootScope,
    FeatureTypeFactory,
    ogcFactory,
    gcWMS,
    gcStyleFactory,
    $http,
    PortalsFactory
  ) {
    return {
      templateUrl: 'js/XG/widgets/ancapp/main/views/mapFilter.html',
      scope: {
        doss: '=doss',
        ftidoss: '=ftidoss',
        resultdoss: '=resultdoss',
        filtrecontrole: '=filtrecontrole',
      },
      restrict: 'EA',
      link: {
        pre: function(scope, elt, attrs, ctrl) {
          // -----------------------------------------------
          // GCMAP INIT
          // -----------------------------------------------

          scope.map = new ol.Map({
            layers: [
              new ol.layer.Tile({
                source: new ol.source.OSM(),
              }),
            ],
            target: 'doss_map',
            controls: ol.control.defaults({
              attribution: false,
              attributionOptions: {
                collapsible: false,
              },
            }),
            view: new ol.View({
              projection: 'EPSG:3857',
              center: [0, 0],
              minResolution: 0.03732276771737122,
              zoom: 10,
            }),
          });
        },
        post: function(scope, element, attr) {
          console.log(scope.ftidoss);
          console.log(scope.doss);

          var portalid = PortalsFactory.getPortalId();

          scope.fid = [];
          for (var i = 0; i < scope.doss.length; i++) {
            scope.fid.push(scope.doss[i].id);
          }
          var cql_filter = '1=1';
          /*  if (scope.fid.length == 0) {
                        cql_filter = '1=2';
                    } else if (scope.fid.length > 0) {
                        //cql_filter = "IN('" + scope.fid.join('\',\'') + "')";
                        cql_filter = "type_dernier_controle='"+scope.filtrecontrole+"'";
                    }*/
          if (scope.filtrecontrole && scope.filtrecontrole != 'tous') {
            cql_filter = "type_dernier_controle='" + scope.filtrecontrole + "'";
          }

          // afficher et zoomer sur les features
          var setExtent = function() {
            if (angular.isUndefined(scope.fid) || scope.fid.length == 0) {
              FeatureTypeFactory.getExtent(scope.ftidoss.uid, 'EPSG:3857').then(
                function(res) {
                  scope.map.getView().fit(res.data, scope.map.getSize());
                }
              );
            } else {
              //recuperer une feature par fid et ftid
              var promise = ogcFactory.getfeatures(
                'GetFeature',
                'WFS',
                '1.0.0',
                scope.ftidoss.uid,
                'json',
                'EPSG:3857',
                cql_filter
              );
              promise.then(function(res) {
                //creer une nouvelle source pour cette feature
                scope.coll = res.data;
                scope.vectorSource = new ol.source.Vector({});
                var parser = new ol.format.GeoJSON();
                for (var i = 0; i < res.data.features.length; i++) {
                  scope.vectorSource.addFeature(
                    parser.readFeature(res.data.features[i])
                  );
                }
                //RECUPERER L'EXTENT DE LA SOURCE
                scope.map
                  .getView()
                  .fit(scope.vectorSource.getExtent(), scope.map.getSize());
                if (scope.zoom) {
                  scope.map.getView().setZoom(parseInt(scope.zoom));
                }
              });
            }
          };
          scope.evtonfinish = function() {
            console.log(scope.dossiersSelected);
          };

          //afficher les features
          var afficherFeatures = function() {
            FeatureTypeFactory.get().then(function(res) {
              // adapte aux modification de FeatureFactory.get (doit utiliser res et non plus res.data)
              for (var i = 0; i < res.length; i++) {
                if (res[i].uid === scope.ftidoss.uid) {
                  scope.map.addLayer(
                    new ol.layer.Tile({
                      source: new ol.source.TileWMS({
                        url:
                          '/services/' +
                          portalid +
                          '/geoserver/wms?token=' +
                          localStorage.auth_token,
                        params: {
                          LAYERS: portalid + ':' + res[i].name,
                          TILED: true,
                          CQL_FILTER: cql_filter,
                        },
                        serverType: 'geoserver',
                      }),
                    })
                  );
                }
              }
            });
          };

          setExtent();
          afficherFeatures();

          var select = new ol.interaction.Select();
          scope.map.addInteraction(select);
          scope.selectedFeatures = select.getFeatures();
          var dragBoxStyle = gcStyleFactory.getStyle('selectrectangle');
          scope.dragBox = new ol.interaction.DragBox({
            condition: function(evt) {
              // scope.altKeyPressed = evt.originalEvent.altKey;
              //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.dragBox.getActive();
            },
            style: dragBoxStyle,
          });
          scope.dragBox.setActive(false);

          scope.dragBox1 = new ol.interaction.DragBox({
            condition: function(evt) {
              // scope.altKeyPressed = evt.originalEvent.altKey;
              //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.dragBox1.getActive();
            },
            style: dragBoxStyle,
          });
          scope.dragBox1.setActive(false);
          scope.removeAllDossier = function() {
            /////////////////////////////////////////////
            var cql_filter1 = '1=1';
            var promise = ogcFactory.getfeatures(
              'GetFeature',
              'WFS',
              '1.0.0',
              scope.ftidoss.uid,
              'json',
              'EPSG:3857',
              cql_filter1
            );
            promise.then(function(res) {
              if (scope.selectedFeatures) {
                scope.selectedFeatures.clear();
              }
              //creer une nouvelle source pour cette feature
              scope.coll = res.data;
              scope.resultdoss = scope.coll;
              scope.removed = true;
            });

            //scope.resultdoss={};
          };

          scope.selectFeatures = function() {
            if (scope.dragBox1.getActive() == true) {
              scope.dragBox1.setActive(false);
            }
            scope.dragBox.setActive(true);
            scope.map.addInteraction(scope.dragBox);
            scope.dragBox.on('boxend', function() {
              // features that intersect the box are added to the collection of
              // selected features
              if (scope.selectedFeatures) {
                scope.selectedFeatures.clear();
              }
              var extent = scope.dragBox.getGeometry().getExtent();
              scope.vectorSource.forEachFeatureIntersectingExtent(
                extent,
                function(feature) {
                  scope.selectedFeatures.push(feature);
                }
              );
              //console.log(scope.selectedFeatures);
              // URL de rcup des objets
              // var filter = gclayers.getSelectFilterasStringuid(map);
              var geometryExtent = scope.dragBox.getGeometry().getExtent();
              var leftX = geometryExtent[0];
              var bottomY = geometryExtent[1];
              var rightX = geometryExtent[2];
              var topY = geometryExtent[3];
              //var catchments_url = '/geoserver/'+PortalsFactory.getPortalId()+'/ows?service=WFS&version=1.0.0&request=GetFeature&typeName='+ filter +'&outputformat=json&srsName='+map.getView().getProjection().getCode()+'&bbox=' + scope.dragBox.getGeometry().getExtent() +','+map.getView().getProjection().getCode();
              var catchments_url =
                '/services/' +
                PortalsFactory.getPortalId() +
                '/ogc/getfeat?service=WFS&version=1.0.0&request=GetFeature&typeName=' +
                scope.ftidoss.uid +
                '&outputformat=json&srsName=' +
                scope.map
                  .getView()
                  .getProjection()
                  .getCode() +
                '&cql_filter=INTERSECTS(geom, POLYGON((' +
                leftX +
                ' ' +
                bottomY +
                ',' +
                rightX +
                ' ' +
                bottomY +
                ',' +
                rightX +
                ' ' +
                topY +
                ',' +
                leftX +
                ' ' +
                topY +
                ',' +
                leftX +
                ' ' +
                bottomY +
                ')))';
              var promise = $http.get(catchments_url);
              var promise2 = promise.then(function(res) {
                scope.resultdoss = res.data;
                //SelectManager.addFeaturesFromGeojson(scope.result);
                //scope.$apply();
              });

              promise2.then(function(res) {
                scope.dragBox.setActive(false);
                scope.map.removeInteraction(scope.dragBox);
                //scope.onfinish();
              });
            });

            // clear selection when drawing a new box and when clicking on the map
            scope.dragBox.on('boxstart', function() {});
          };

          var getIds = function(feats) {
            var tab = [];
            for (var i = 0; i < feats.length; i++) {
              tab.push(feats[i].id);
            }
            return tab;
          };

          var getIdsSF = function(feats) {
            var tab = [];
            for (var i = 0; i < feats.length; i++) {
              tab.push(feats[i].getId());
            }
            return tab;
          };

          scope.selectFeaturesPlus = function() {
            if (scope.dragBox.getActive() == true) {
              scope.dragBox.setActive(false);
            }
            if (scope.dragBox1.getActive() == true) {
              scope.dragBox1.setActive(false);
              scope.map.removeInteraction(scope.dragBox1);
            } else {
              //}
              scope.dragBox1.setActive(true);

              scope.map.addInteraction(scope.dragBox1);
              //scope.removeAllDossier();
              scope.dragBox1.on('boxend', function() {
                var extent = scope.dragBox1.getGeometry().getExtent();
                scope.vectorSource.forEachFeatureIntersectingExtent(
                  extent,
                  function(feature) {
                    // console.log(feature);
                    var tab = scope.selectedFeatures.getArray();
                    var ids = getIdsSF(tab);
                    if (ids.indexOf(feature.getId()) === -1) {
                      scope.selectedFeatures.push(feature);
                    }
                  }
                );
                //console.log(scope.selectedFeatures);
                // URL de rcup des objets
                // var filter = gclayers.getSelectFilterasStringuid(map);
                var geometryExtent = scope.dragBox1.getGeometry().getExtent();
                var leftX = geometryExtent[0];
                var bottomY = geometryExtent[1];
                var rightX = geometryExtent[2];
                var topY = geometryExtent[3];
                //var catchments_url = '/geoserver/'+PortalsFactory.getPortalId()+'/ows?service=WFS&version=1.0.0&request=GetFeature&typeName='+ filter +'&outputformat=json&srsName='+map.getView().getProjection().getCode()+'&bbox=' + scope.dragBox.getGeometry().getExtent() +','+map.getView().getProjection().getCode();
                var catchments_url =
                  '/services/' +
                  PortalsFactory.getPortalId() +
                  '/ogc/getfeat?service=WFS&version=1.0.0&request=GetFeature&typeName=' +
                  scope.ftidoss.uid +
                  '&outputformat=json&srsName=' +
                  scope.map
                    .getView()
                    .getProjection()
                    .getCode() +
                  '&cql_filter=INTERSECTS(geom, POLYGON((' +
                  leftX +
                  ' ' +
                  bottomY +
                  ',' +
                  rightX +
                  ' ' +
                  bottomY +
                  ',' +
                  rightX +
                  ' ' +
                  topY +
                  ',' +
                  leftX +
                  ' ' +
                  topY +
                  ',' +
                  leftX +
                  ' ' +
                  bottomY +
                  ')))';
                var promise = $http.get(catchments_url);
                var promise2 = promise.then(function(res) {
                  if (
                    scope.resultdoss &&
                    scope.resultdoss.features &&
                    scope.resultdoss.features.length > 0
                  ) {
                    var tabRes = scope.resultdoss;
                    if (scope.removed == true) {
                      tabRes.features = [];
                      tabRes.totalFeatures = 0;
                      scope.removed = false;
                    }
                    var res2 = res.data;
                    var ids = getIds(res.data.features);
                    var tf = res2.totalFeatures;
                    for (var i = 0; i < tabRes.features.length; i++) {
                      if (ids.indexOf(tabRes.features[i].id) === -1) {
                        res2.features.push(tabRes.features[i]);
                        tf++;
                      }
                    }
                    res2.totalFeatures = tf;
                    scope.resultdoss = res2;
                    //scope.resultdoss.totalFeatures = tf;
                  } else {
                    scope.resultdoss = res.data;
                  }
                  //SelectManager.addFeaturesFromGeojson(scope.result);
                  //scope.$apply();
                });

                promise2.then(function(res) {
                  //scope.dragBox1.setActive(false);
                  //scope.map.removeInteraction(scope.dragBox1);
                  //scope.onfinish();
                });
              });

              // clear selection when drawing a new box and when clicking on the map
              scope.dragBox1.on('boxstart', function() {});
            }
          };
        },
      },
    };
  };

  filterMap.$inject = [
    'ngDialog',
    '$rootScope',
    'FeatureTypeFactory',
    'ogcFactory',
    'gcWMS',
    'gcStyleFactory',
    '$http',
    'PortalsFactory',
  ];
  return filterMap;
});
