'use strict';
define(function() {
  var mapPositionPicker = function(
    ngDialog,
    $rootScope,
    $timeout,
    $http,
    gaDomUtils,
    gaJsUtils,
    gcWMS,
    FeatureTypeFactory,
    kisGeocodageFactory,
    $filter
  ) {
    return {
      templateUrl:
        'js/XG/modules/common/views/directives/map_position_picker.html',
      scope: {
        position: '=',
        bbox: '=?',
        center: '=?', // EPSG:3857
        zoom: '@?',
        service: '@?', // 'google' or 'nominatim' or KisGeocodage id
        nombreposition: '@?',
        getBbox: '=?', // if set to true, we retrieve the bbox,
        displayLayers: '=?', // array of fti to display
        map: '=?',
        cannotModify: '=?',
        displayFeaturesConfig: '=?', // used with features-config  directive,
        multipoint: '=?', // allow to pick multiple point
        apptype: '=?',
      },
      restrict: 'E',
      link: function(scope, element, attr) {
        //Objet retourne
        scope.position = {};

        //RB temporary disabled
        scope.nombreposition = false;

        // TMP FIX RB
        //address choisie
        scope.placeData = {};
        //Form des infos address
        scope.infoService = false;
        //Changer le color du botton Draw
        scope.dessin = false;

        var source, map, dialog_map_position_picker, vector, draw;

        //console.log(scope.position);

        //ng-Dialog
        scope.openMapDialog = function() {
          scope.position = {};
          scope.placeData.place = false;

          // si on a une map  (passe en parametre)
          if (scope.map) {
            map = scope.map;
            scope.activerDessin();
          } else {
            dialog_map_position_picker = ngDialog.open({
              template:
                'js/XG/modules/common/views/directives/map_position_picker_dialog.html',
              className: 'ngdialog-theme-plain fullScreen nopadding ',
              closeByDocument: false,
              showClose: false,
              scope: scope,
            });
          }
          /*        scope.position = {};
                     scope.placeData.place = false;
                     dialog_map_position_picker = ngDialog.open({
                     template: 'js/XG/modules/common/views/directives/map_position_picker_dialog.html',
                     className: 'ngdialog-theme-plain fullScreen nopadding ',
                     closeByDocument: false,
                     showClose: false,
                     scope: scope
                     });*/
        };

        //Click sur la map pour recuperer les coords
        //Condition avec attribute 'nombreposition'='3' dans la directive
        if (scope.nombreposition) {
          scope.coords = [];
        }

        // retrieve the bbox
        scope.setBboxFromMap = function() {
          scope.bbox = map.getView().calculateExtent(map.getSize());
          dialog_map_position_picker.close();
        };

        //Activer le dessin
        scope.activerDessin = function() {
          if (!scope.map) {
            if (scope.dessin == true) {
              scope.dessin = false;
              map.removeInteraction(draw);
              // source.clear();
              return false;
            }
            scope.dessin = true;
          }
          if (
            scope.nombreposition &&
            scope.coords.length == scope.nombreposition
          ) {
            return false;
          }

          draw = new ol.interaction.Draw({
            source: source,
            type: 'Point',
            maxPoints: 1,
          });

          draw.set('gctype', 'kis');
          draw.set('interaction', 'Draw');
          draw.set('widget', 'mappicker');

          if (vector) {
            map.getLayers().insertAt(9999, vector);
          }

          //Click sur la map
          draw.on('drawend', function(evt) {
            //transformer les coords de Openlayer
            if (scope.nombreposition) {
              //  scope.coords.push(ol.proj.transform(evt.feature.getGeometry().getCoordinates(), 'EPSG:3857', 'EPSG:4326'));
              scope.coords.push(
                ol.proj.transform(
                  evt.feature.getGeometry().getCoordinates(),
                  map
                    .getView()
                    .getProjection()
                    .getCode(),
                  'EPSG:4326'
                )
              );
            } else {
              //  scope.coords = ol.proj.transform(evt.feature.getGeometry().getCoordinates(), 'EPSG:3857', 'EPSG:4326');
              scope.coords = ol.proj.transform(
                evt.feature.getGeometry().getCoordinates(),
                map
                  .getView()
                  .getProjection()
                  .getCode(),
                'EPSG:4326'
              );
            }

            var url;
            if (angular.isUndefined(scope.service)) {
              $timeout(function() {
                scope.position.coordinates = scope.coords;

                if (!scope.nombreposition) {
                  scope.placeData.place = true;
                }
                if (
                  scope.nombreposition &&
                  scope.coords.length == scope.nombreposition
                ) {
                  scope.placeData.place = true;
                  map.removeInteraction(draw);
                  scope.dessin = false;
                }
              }, 0);
            } else {
              //Action en cours
              gaDomUtils.showGlobalLoader();
              var promise;
              if (scope.service == 'google') {
                //url = 'https://maps.googleapis.com/maps/api/geocode/json?key=AIzaSyBT9fBCbBmtzVOWmTZjNR55y94_zfG3KfM&latlng=' + scope.coords[1] + ',' + scope.coords[0];
                url =
                  'https://maps.googleapis.com/maps/api/geocode/json?latlng=' +
                  scope.coords[1] +
                  ',' +
                  scope.coords[0];
              } else if (scope.service == 'nominatim') {
                url =
                  'https://nominatim.openstreetmap.org/reverse?format=json&lat=' +
                  scope.coords[1] +
                  '&lon=' +
                  scope.coords[0] +
                  '&zoom=18&addressdetails=1';
              } else {
                promise = kisGeocodageFactory.reverse(
                  kisGeocodageFactory.getGeocoderConfigFromId(scope.service)
                    .url,
                  scope.coords
                );
                gaDomUtils.hideGlobalLoader();
              }
              if (scope.service == 'google' || scope.service == 'nominatim') {
                promise = $http.get(url);
              }
              promise.then(
                function(res) {
                  console.log(res.data);
                  scope.infoService = scope.service;
                  if (scope.service == 'google') {
                    if (res.data.results.length) {
                      scope.position.infos = res.data.results;
                      if (res.data.results.length) {
                        scope.placeData.place = res.data.results[0];
                      }
                    } else {
                      require('toastr').warning(
                        'Erreur lors de la récupération de la position, retenter dans quelques secondes.',
                        '',
                        {
                          positionClass: 'toast-bottom-left',
                        }
                      );
                      scope.placeData = {};
                    }
                  } else if (scope.service == 'nominatim') {
                    scope.position.infos = res.data;
                    scope.placeData.place = true;
                  } else {
                    scope.position.infos = res.data.features[0];
                    scope.placeData.place = true;
                  }
                  scope.dessin = false;
                  scope.position.coordinates = scope.coords;

                  //Sortir d'action en cours
                  gaDomUtils.hideGlobalLoader();
                },
                function() {
                  gaDomUtils.hideGlobalLoader();
                }
              );
            }

            if (angular.isUndefined(scope.nombreposition) && !scope.map) {
              source.clear();
            }
          });

          map.addInteraction(draw);
        };

        $rootScope.$on('MapPositionPickerRemoveDraw', function() {
          if (map && draw) {
            map.removeInteraction(draw);
          }
        });

        //Supprimer des coords du tableau
        scope.supprimerCoordsDuTableau = function(index) {
          scope.placeData.place = false;
          scope.coords.splice(index, 1);
          source.removeFeature(source.getFeatures()[index]);
        };

        var clearCoords = function() {
          scope.infoService = false;
          scope.dessin = false;
          scope.coords = [];
          scope.position = {};
          scope.placeData.place = false;
        };

        //Annuler coords
        scope.resetCoordsMapPicker = function() {
          clearCoords();
          map.removeInteraction(draw);
          source.clear();
        };

        //Fermer Dialog
        scope.fermerDialogMapPicker = function() {
          clearCoords();
          source.clear();
          map.removeInteraction(draw);
          dialog_map_position_picker.close();
        };

        //Annuler les infos du google/ moninatin
        scope.resetPickedPosition = function() {
          clearCoords();
          // scope.bbox = [];
        };

        //Comfimer un address qu'on a chousi
        scope.confimerMapPickerCoords = function() {
          if (scope.service == 'google') {
            scope.position.infos = scope.placeData;
          } else {
            // scope.placeData.place = false;
            scope.infoService = false;
          }
          scope.coords = [];
          scope.dessin = false;
          map.removeInteraction(draw);
          source.clear();
          dialog_map_position_picker.close();
          $rootScope.$broadcast('PositionFromMapPositionPickerChange');
        };

        /**
                 * reset zIndex for layers
                /* *!/
                $rootScope.$on('featuresConfigLayersDisplayChange', function (event, data) {
                    if(data.name=='mapPositionPicker'){
                        var array = [];
                        data.features.forEach(function (f) {
                            var l = gcWMS.getOlLayerFromFeaturetypeInfo(f);
                            map.removeLayer(l);
                            array.unshift(l);
                        });
                        array.forEach(function (l){
                            map.addLayer(l);
                        })
                    }
                });*/

        //title of button
        scope.possitionner = $filter('translate')(
          'common.directives.mappicker.position'
        );

        //Listen
        $rootScope.$on('ngDialog.opened', function(e, $dialog) {
          if (
            angular.isUndefined(dialog_map_position_picker) ||
            angular.isUndefined(dialog_map_position_picker.id)
          ) {
            return false;
          }

          if (dialog_map_position_picker.id != $dialog[0].id) {
            return false;
          }

          source = new ol.source.Vector({
            wrapX: false,
          });

          vector = new ol.layer.Vector({
            source: source,
            style: new ol.style.Style({
              image: new ol.style.Icon({
                anchor: [0.5, 46],
                anchorXUnits: 'fraction',
                anchorYUnits: 'pixels',
                src: 'img/common/map_directive_picker.png',
              }),
            }),
          });

          if (angular.isUndefined(scope.center)) {
            scope.center = [0, 0];
          }

          if (angular.isUndefined(scope.zoom)) {
            scope.zoom = 4;
          }

          map = new ol.Map({
            layers: [
              new ol.layer.Tile({
                source: new ol.source.OSM(),
              }),
              vector,
            ],
            target: 'map_position_picker',
            controls: ol.control.defaults(),
            view: new ol.View({
              center: scope.center,
              zoom: scope.zoom,
              projection: 'EPSG:3857',
              minResolution: 0.03732276771737122,
            }),
          });

          scope.currentMap = map;
          if (
            angular.isDefined(scope.displayLayers) &&
            ancAppAndroid == 'undefined'
          ) {
            scope.displayLayers.forEach(function(f) {
              var l = gcWMS.getOlLayerFromFeaturetypeInfo(f);
              map.addLayer(l);
            });
          }

          if (angular.isDefined(scope.bbox)) {
            map.getView().fit(scope.bbox, map.getSize());
          }
        });

        scope.capitalize = function(x) {
          return gaJsUtils.capitalizeFirstLetter(x);
        };
      },
    };
  };

  mapPositionPicker.$inject = [
    'ngDialog',
    '$rootScope',
    '$timeout',
    '$http',
    'gaDomUtils',
    'gaJsUtils',
    'gcWMS',
    'FeatureTypeFactory',
    'kisGeocodageFactory',
    '$filter',
  ];
  return mapPositionPicker;
});
