'use strict';
define(function() {
  var banoInfo = function($http, kisGeocodageFactory, $rootScope) {
    return {
      templateUrl: 'js/XG/modules/common/views/directives/bano_info.html',
      scope: {
        resultat: '=',
        type: '@',
        service: '@?', // id of Kis Geocodage
      },
      restrict: 'EA',
      link: function(scope, element, attr) {
        //Initiation de valeur
        scope.selectedAddress = {};
        var addressInfos;

        //la methode pour recuperer les infos automatiquement
        scope.getBanoInfos = function(requete) {
          if (requete == '' || requete == undefined) {
            return false;
          }

          var urlType = scope.type == 'postcode' ? 'city' : scope.type;
          var promise;
          if (!scope.service) {
            promise = $http.get(
              'https://api-adresse.data.gouv.fr/search/?q=' +
                requete +
                '&type=' +
                urlType
            );
          } else {
            promise = kisGeocodageFactory.search(
              kisGeocodageFactory.getGeocoderConfigFromId(scope.service).url,
              requete,
              urlType
            );
          }

          return promise.then(function(res) {
            addressInfos = [];
            var view;
            for (var i = 0; i < res.data.features.length; i++) {
              if (scope.type == 'city') {
                view = res.data.features[i].properties.city;
              } else if (scope.type == 'postcode') {
                view = res.data.features[i].properties.postcode;
              } else if (scope.type == 'street') {
                view = res.data.features[i].properties.label;
              }
              addressInfos.push({
                view: view,
                data: res.data.features[i],
              });
            }
            return addressInfos;
          });
        };

        //listen '$typeahead.select'
        scope.$on('$typeahead.select', function() {
          scope.resultat = scope.selectedAddress;
        });
      },
    };
  };

  banoInfo.$inject = ['$http', 'kisGeocodageFactory', '$rootScope'];
  return banoInfo;
});
