'use strict';
define(function() {
  var what3wordswidget = function(
    $http,
    $translate,
    $rootScope,
    $filter,
    gaJsUtils,
    What3WordFactory,
    $sce
  ) {
    return {
      templateUrl:
        'js/XG/widgets/mapapp/what3words/views/what3wordswidget.html',
      restrict: 'A',
      scope: {
        map: '=',
      },
      link: function(scope, elt, attrs, ctrl) {
        scope.$on('closeTools_geolocalisationwidget', function(event, arg) {
          if (arg.directive === 'geolocalisationwidget') {
            if (
              scope.vectorLayer &&
              scope.vectorLayer instanceof ol.layer.Vector
            )
              scope.map.removeLayer(scope.vectorLayer);
          }
        });
        scope.$on('closeToolsBar_toolbarposition', function(event, arg) {
          console.log(event);
          console.log(arg);
          if (scope.vectorLayer && scope.vectorLayer instanceof ol.layer.Vector)
            scope.map.removeLayer(scope.vectorLayer);
        });

        scope.drawinteraction = {};
        scope.vectorSource;

        /**
         * [On récupère la clé d'API définie au niveau du portail si n'est pas valide, le module n'est pas affiché]
         */
        if (
          !gaJsUtils.checkNestedProperty(
            'portal.parameters.apikey.what3words',
            $rootScope.xgos
          )
        ) {
          scope.hide = true;
          return;
        } else {
          var apiKeyW3W = $rootScope.xgos.portal.parameters.apikey.what3words;
        }

        if (!apiKeyW3W || apiKeyW3W === '') {
          scope.hide = true;
        }

        scope.what3words = {};

        scope.what3words.splitValue = function(words) {
          if (words.length > 0 && words.split('.', 3).length > 2) {
            var promise = What3WordFactory.autoSuggest(words);
            promise.then(function(res) {
              console.log(res);
              scope.what3words.autoSuggestValue = [];
              if (angular.isDefined(res.data.features)) {
                res.data.features.forEach(function(f) {
                  var att = $sce.trustAsHtml(
                    '<i class="flag flag-' +
                      f.properties.country +
                      '"></i> ' +
                      f.properties.words
                  );
                  var value = f.properties.words;
                  scope.what3words.autoSuggestValue.push({
                    html: att,
                    words: value,
                  });
                });
              }
            });
          }
        };

        scope.what3words.setWords = function() {
          if (
            angular.isDefined(scope.what3words.selected) &&
            scope.what3words.selected.words.length > 0 &&
            scope.what3words.selected.words.split('.', 3).length == 3
          ) {
            scope.what3words.firstWord = scope.what3words.selected.words.split(
              '.',
              3
            )[0];
            scope.what3words.secondWord = scope.what3words.selected.words.split(
              '.',
              3
            )[1];
            scope.what3words.thirdWord = scope.what3words.selected.words.split(
              '.',
              3
            )[2];
          } else {
            delete scope.what3words.firstWord;
            delete scope.what3words.secondWord;
            delete scope.what3words.thirdWord;
          }
        };

        /**.
         * Localisation avec l'API What3Words
         * @return {Object} [promise]
         */
        scope.searchAdress = function() {
          var first = scope.what3words.firstWord;
          var second = scope.what3words.secondWord;
          var third = scope.what3words.thirdWord;

          /**
           * Si le layer existe, on le remove
           */
          if (scope.vectorLayer && scope.vectorLayer instanceof ol.layer.Vector)
            scope.map.removeLayer(scope.vectorLayer);

          /**
           * [Construction de l'url à requêter]
           * @param obligatoire
           *        addr (combinaison de mots ex. index.home.raft)
           *        key (clé api valide)
           */
          /*var url = "https://api.what3words.com/v2/forward?addr="
                                +first+"."+second+"."+third+
                                "&display=full&format=geojson&key="+apiKeyW3W+"&lang="+localStorage.getItem('current_language')+"&display=full";*/

          if (first && second && third) {
            if (!apiKeyW3W || apiKeyW3W == '') {
              require('toastr').error(
                $filter('translate')('what3words.keyerror')
              );
            } else {
              //var promise = $http.get(url);
              var promise = What3WordFactory.search(first, second, third);
              promise.then(
                function(res) {
                  /**
                   * On vérifie le status de la réponse, si invalide on renvoie l'erreur
                   */
                  if (
                    res.data.properties.status.code === 300 ||
                    res.data.properties.status.code === 102
                  ) {
                    var errorCase = res.data.properties.status.code;
                    require('toastr').error(
                      $filter('translate')('what3words.' + errorCase)
                    );

                    /**
                     * Si la requête est valide, on récupère la géométrie et on l'affiche au centre
                     */
                  } else if (res.data.geometry) {
                    var coordp = ol.proj.transform(
                      [
                        res.data.geometry.coordinates[0],
                        res.data.geometry.coordinates[1],
                      ],
                      'EPSG:4326',
                      scope.map.getView().getProjection()
                    );

                    var x = coordp[0];
                    var y = coordp[1];

                    var view = scope.map.getView();
                    /*var pan = ol.animation.pan({
                                            duration: 500,
                                            source: (view.getCenter())
                                    });*/
                    view.animate({
                      duration: 500,
                      source: view.getCenter(),
                    });

                    var side = 3;
                    var coordsquare = [];
                    var x1 = coordp[0] - side / 2;
                    var x4 = x1;
                    var x2 = coordp[0] + side / 2;
                    var x3 = x2;
                    var y1 = coordp[1] - side / 2;
                    var y2 = y1;
                    var y3 = coordp[1] + side / 2;
                    var y4 = y3;

                    coordsquare.push(
                      [x1, y1],
                      [x2, y2],
                      [x3, y3],
                      [x4, y4],
                      [x1, y1]
                    );

                    view.setZoom(19);
                    view.setCenter([x, y]);

                    var localisation = new ol.Feature({
                      geometry: new ol.geom.Polygon([coordsquare]),
                    });

                    var stroke = new ol.style.Stroke({
                      color: 'black',
                      width: 1,
                    });
                    var fill = new ol.style.Fill({
                      color: 'blue',
                    });

                    var stylee = new ol.style.Style({
                      fill: fill,
                      stroke: stroke,
                    });

                    localisation.setStyle(stylee);

                    var vectorSource = new ol.source.Vector();

                    vectorSource.addFeature(localisation);

                    scope.vectorLayer = new ol.layer.Vector({
                      source: vectorSource,
                    });

                    scope.map.addLayer(scope.vectorLayer);
                  }

                  /**
                   * Si la requête est invalide, on renvoie l'erreur
                   */
                },
                function(res) {
                  var errorCase = res.status.toString();
                  require('toastr').error(
                    $filter('translate')('what3words.' + errorCase)
                  );
                  console.log(errorCase);
                  scope.hide = true;
                }
              );
              return promise;
            }
          }
        };
      },
    };
  };

  what3wordswidget.$inject = [
    '$http',
    '$translate',
    '$rootScope',
    '$filter',
    'gaJsUtils',
    'What3WordFactory',
    '$sce',
  ];
  return what3wordswidget;
});
