'use strict';
define(function() {
  var gctoolbargeocoderreversew3w = function(
    What3WordFactory,
    gaJsUtils,
    gaDomUtils,
    $rootScope,
    $compile,
    $filter,
    gcInteractions
  ) {
    return {
      templateUrl:
        'js/XG/widgets/mapapp/geocoderreversew3w/views/gctoolbargeocoderreversew3w.html',
      restrict: 'EA',

      link: function(scope, element, attrs, ctrl) {
        scope.isActive = false;

        var btnElt = $(element.children()[0]);
        btnElt.bind('click', function($event) {
          if (
            $event.target.nodeName != 'BUTTON' &&
            $event.target.nodeName != 'SPAN' &&
            $event.target.nodeName != 'IMG'
          ) {
            return false;
          }

          if (scope.isActive) {
            scope.isActive = false;
            removePopups();
            $('.mapGeocoderPicker').remove();
            scope.draw.setActive(false);
            map.removeInteraction(scope.draw);
          } else {
            if (
              gaJsUtils.checkNestedProperty(
                'portal.parameters.apikey.what3words',
                $rootScope.xgos
              )
            ) {
              scope.apiKeyW3W =
                $rootScope.xgos.portal.parameters.apikey.what3words;
              scope.isActive = true;
              dessin();
              scope.draw.setActive(true);
              map.addInteraction(scope.draw);
            } else {
              require('toastr').error(
                $filter('translate')('what3words.keyerror')
              );
              scope.isActive = false;
              removePopups();
              $('.mapGeocoderPicker').remove();
              scope.draw.setActive(false);
              map.removeInteraction(scope.draw);
            }
          }
        });

        scope.$on('closeToolsBar_gctoolbargeocoderreversew3w', function() {
          if (scope.isActive) $('#toolbargeocoderreversew3w_btn').click();
          scope.isActive = false;
          removePopups();
          $('.mapGeocoderPicker').remove();
          scope.draw.setActive(false);
          map.removeInteraction(scope.draw);
        });

        scope.closeAllPopups = function() {
          removePopups();
        };

        var map = scope.map;
        var features = new ol.Collection();
        var drawStyle = new ol.style.Style({
          fill: new ol.style.Fill({
            color: 'rgba(255, 255, 255, 0.5)',
          }),
          stroke: new ol.style.Stroke({
            color: '#3498db',
            width: 2,
          }),
          image: new ol.style.Circle({
            radius: 7,
            fill: new ol.style.Fill({
              color: '#3498db',
            }),
          }),
        });

        /**
         * dessin
         */
        var dessin = function() {
          map.removeInteraction(scope.draw);

          scope.draw = new ol.interaction.Draw({
            features: features,
            type: 'Point',
            style: drawStyle,
          });

          scope.draw.set('gctype', 'kis');
          scope.draw.set('interaction', 'Draw');
          scope.draw.set('widget', 'select');
          scope.draw.setActive(false);
          gcInteractions.setCurrentToolBar(scope.toolBarWidget);
          map.addInteraction(scope.draw);

          scope.draw.on('drawend', function(e) {
            if (scope.isActive == false) {
              scope.draw.setActive(false);
              map.removeInteraction(scope.draw);
              return false;
            }

            var coords = e.feature.getGeometry().getCoordinates();
            var coords_4326 = ol.proj.transform(
              coords,
              map
                .getView()
                .getProjection()
                .getCode(),
              'EPSG:4326'
            );

            if (!scope.apiKeyW3W || scope.apiKeyW3W == '') {
              require('toastr').error(
                $filter('translate')('what3words.keyerror')
              );
              return false;
            }
            gaDomUtils.showGlobalLoader();
            var promise = What3WordFactory.reverse(coords_4326);

            promise.then(
              function(res) {
                gaDomUtils.hideGlobalLoader();

                if (angular.isDefined(res.data.words)) {
                  var text_content = res.data.words;
                  setPopups(coords, text_content);
                } else {
                  require('toastr').error('Rien trouvé !');
                }
              },
              function(res) {
                if (res.data.status === 401) {
                  var errorCase = res.data.status;
                  require('toastr').error(
                    $filter('translate')('what3words.' + errorCase)
                  );
                }
                gaDomUtils.hideGlobalLoader();
              }
            );
          });
        };

        /**
         * close Popup
         * @param event
         */
        scope.closeGeocodeReversePopup = function(event) {
          var popup = angular.element(event.target).parent();
          popup.remove();
        };
        /**
         * open popup
         * @param coords
         * @param text_content
         */
        var setPopups = function(coords, text_content) {
          var overlayz = [];

          var coordinate = coords;
          var uniqid = 'geocoderpopup_' + Date.now();
          var tpl =
            ' <div id="' +
            uniqid +
            '" class="ol-popup annotationPopup" >' +
            '<div class="popup-content"></div>' +
            '<div class="ol-popup-closer-geocoder" ng-click="closeGeocodeReversePopup($event)"></div>' +
            '</div>';

          angular
            .element(document)
            .find('body')
            .eq(0)
            .append($compile(tpl)(scope));

          var container = document.getElementById(uniqid);

          $(container)
            .find('.popup-content')
            .html(text_content);

          var overlay = new ol.Overlay({
            element: container,
            autoPan: true,
            insertFirst: false,
            autoPanAnimation: {
              duration: 250,
            },
          });
          overlay.set('origin', uniqid);

          map.addOverlay(overlay);
          overlay.setPosition(coordinate);
        };

        /**
         * remove all popups
         */
        var removePopups = function() {
          for (var i = map.getOverlays().getLength() - 1; i >= 0; i -= 1) {
            var overlay = map.getOverlays().getArray()[i];
            if (overlay.get('origin').indexOf('geocoderpopup_') == 0) {
              map.removeOverlay(overlay);
            }
          }
        };

        /**
         *
         * @returns {number}
         */
        scope.renderNumPopovers = function() {
          var res = 0;
          for (var i = map.getOverlays().getLength() - 1; i >= 0; i -= 1) {
            var overlay = map.getOverlays().getArray()[i];
            if (overlay.get('origin').indexOf('geocoderpopup_') == 0) {
              res++;
            }
          }
          return res;
        };
      },
    };
  };

  gctoolbargeocoderreversew3w.$inject = [
    'What3WordFactory',
    'gaJsUtils',
    'gaDomUtils',
    '$rootScope',
    '$compile',
    '$filter',
    'gcInteractions',
  ];
  return gctoolbargeocoderreversew3w;
});
