'use strict';
define(function() {
  var positionAutoComplete = function(
    $http,
    $timeout,
    kisGeocodageFactory,
    $rootScope,
    $filter
  ) {
    return {
      templateUrl:
        'js/XG/modules/common/views/directives/position_auto_complete.html',
      scope: {
        adresse: '=?',
        button: '@?',
        service: '@',
        defaultValue: '=?',
        allowValueFromText: '=?',
        cannotModify: '=?',
      },
      restrict: 'EA',
      link: function(scope, element, attr) {
        if (angular.isUndefined(scope.service)) scope.service = 'google';

        scope.buttonValue = scope.button;
        scope.buttonAffiche = true;
        scope.adresses = {};

        if (angular.isUndefined(scope.button)) {
          scope.buttonAffiche = false;
        }

        scope.$watch(
          'defaultValue',
          function(defaultValue) {
            setDefaultValue();
          },
          1
        );

        // set a default value and a default array (return by getInformationsFromAddress)
        var defaultArray = [];
        var setDefaultValue = function() {
          if (angular.isDefined(scope.defaultValue)) {
            defaultArray = [{ value: scope.defaultValue }];
            scope.adresses = { res: { value: scope.defaultValue } };
          }
        };
        setDefaultValue();

        scope.getInformationsFromAddress = function(address) {
          if (address == '' || address == undefined) {
            if (angular.isDefined(scope.defaultValue)) {
              return defaultArray;
            } else {
              return false;
            }
          }

          if (scope.service == 'google') {
            var params = { address: address, sensor: false };

            // return $http.get('https://maps.googleapis.com/maps/api/geocode/json?key=AIzaSyBT9fBCbBmtzVOWmTZjNR55y94_zfG3KfM', {params: params})
            return $http
              .get('https://maps.googleapis.com/maps/api/geocode/json', {
                params: params,
              })
              .then(function(res) {
                for (var i = 0; i < res.data.results.length; i++) {
                  res.data.results[i].value =
                    res.data.results[i].formatted_address;
                }
                return res.data.results;
              });
          } else if (scope.service == 'nominatim') {
            return $http
              .get(
                'https://nominatim.openstreetmap.org/?format=json&q=' + address
              )
              .then(function(res) {
                for (var i = 0; i < res.data.length; i++) {
                  res.data[i].value = res.data[i].display_name;
                }
                return res.data;
              });
          } else if (!scope.service || scope.service == '') {
            require('toastr').error(
              $filter('translate')(
                'common.directives.position_autocomplete.service_vide'
              )
            );
          } else {
            return kisGeocodageFactory
              .search(
                kisGeocodageFactory.getGeocoderConfigFromId(scope.service).url,
                address
              )
              .then(function(res) {
                for (var i = 0; i < res.data.features.length; i++) {
                  res.data.features[i].value =
                    res.data.features[i].properties.label;
                }
                return res.data.features;
              });
          }
        };

        scope.$on('$typeahead.select', function(value, index) {
          if (
            angular.isUndefined(scope.button) &&
            index == scope.adresses.res
          ) {
            scope.adresse = scope.adresses.res;
          }
        });

        if (scope.allowValueFromText) {
          if (angular.isUndefined(scope.button)) {
            scope.$watch(
              'adresses',
              function() {
                scope.adresse = scope.adresses.res;
              },
              1
            );
          }
        }

        scope.enregistrerInfo = function() {
          $timeout(function() {
            scope.adresse = scope.adresses.res;
          });
        };
      },
    };
  };

  positionAutoComplete.$inject = [
    '$http',
    '$timeout',
    'kisGeocodageFactory',
    '$rootScope',
    '$filter',
  ];
  return positionAutoComplete;
});
