'use strict';
define(function() {
  var toolbarselecttool = function(
    $http,
    SelectManager,
    gclayers,
    gcPopup,
    $filter,
    gcRestrictionProvider,
    gcInteractions,
    $timeout,
    $rootScope,
    gaJsUtils,
    PortalsFactory
  ) {
    return {
      templateUrl:
        'js/XG/widgets/mapapp/selecttoolbypoint/views/toolbarselecttoolbypoint.html',
      restrict: 'AE',

      link: function(scope, element) {
        var map = scope.map;
        var pop;
        scope.isActive = false;

        scope.altKeyPressed = false;
        //                var btnElt = $(element.children()[0]);
        var btnElt = $(element[0]);

        scope.$on('closeToolsBar_toolbarselecttoolbypoint', function() {
          if (scope.pointerByPoint.getActive()) {
            deactivate();
            if (pop) {
              pop.close();
              gclayers.clearhighLightFeatures();
              SelectManager.clear();
            }
          }
        });

        scope.pointerByPoint = new ol.interaction.Draw({
          type: 'Point',
          style: new ol.style.Style({}),
          condition: function(e) {
            //console.log(e.originalEvent.shiftKey);
            scope.altKeyPressed = e.originalEvent.ctrlKey;
            return true; //always return true but need to set whether shift key is pressed or not
          },
        });

        scope.pointerByPoint.set('gctype', 'kis');
        scope.pointerByPoint.set('interaction', 'Draw');
        scope.pointerByPoint.set('widget', 'select');
        scope.pointerByPoint.setActive(false);

        btnElt.bind('click', () => {
          if (scope.pointerByPoint.getActive()) {
            deactivate();
          } else {
            activate();
          }
        });

        const deactivate = () => {
          scope.pointerByPoint.setActive(false);
          map.removeInteraction(scope.pointerByPoint);
          if (scope.toolbarInfo){
            scope.toolbarInfo.setActiveBtn(undefined);
          }
        }

        const activate = () => {
          gcInteractions.setCurrentToolBar(scope.toolBarWidget);
          scope.pointerByPoint.setActive(true);
          map.addInteraction(scope.pointerByPoint);
          if (scope.toolbarInfo){
            scope.toolbarInfo.setActiveBtn('toolbarselecttoolbypoint');
          }
        }

        scope.pointerByPoint.on('drawend', function(evt) {
          //   var filter = gclayers.getSelectFilterasString("name");
          var filter = gclayers.getSelectFilterasStringuid(map);
          if (filter != '') {
            var format = new ol.format.GeoJSON();
            var feature = format.writeFeatureObject(evt.feature);

            var x = feature.geometry.coordinates[0];
            var y = feature.geometry.coordinates[1];

            var view = map.getView();
            var resolution = view.getResolution();

            // var pointExtent = [x, y , x, y];
            if (resolution != 'undefined') {
              var leftX = x - 5 * resolution;
              var rightX = x + 5 * resolution;
              var bottomY = y - 5 * resolution;
              var topY = y + 5 * resolution;
            } else {
              leftX = x - 5;
              rightX = x + 5;
              bottomY = y - 5;
              topY = y + 5;
            }

            //                    var catchments_url = '/geoserver/' + PortalsFactory.getPortalId() + '/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=' + filter + '&outputformat=json&srsName=' + map.getView().getProjection().getCode() + '&cql_filter=INTERSECTS(geom, POLYGON((' + leftX + ' ' + bottomY + ',' + rightX + ' ' + bottomY + ',' + rightX + ' ' + topY + ',' + leftX + ' ' + topY + ',' + leftX + ' ' + bottomY + ')))';

            var catchments_url =
              '/services/' +
              PortalsFactory.getPortalId() +
              '/ogc/getfeat?service=WFS&version=1.0.0&request=GetFeature&typeName=' +
              filter +
              '&outputformat=json&srsName=' +
              map
                .getView()
                .getProjection()
                .getCode() +
              '&cql_filter=INTERSECTS(geom, POLYGON((' +
              leftX +
              ' ' +
              bottomY +
              ',' +
              rightX +
              ' ' +
              bottomY +
              ',' +
              rightX +
              ' ' +
              topY +
              ',' +
              leftX +
              ' ' +
              topY +
              ',' +
              leftX +
              ' ' +
              bottomY +
              ')))';

            var promise = $http.get(catchments_url);
            promise.then(
              function(res) {
                if (
                  $rootScope.xgos &&
                  $rootScope.xgos.sector === 'hpo' &&
                  $rootScope.xgos.hpo
                ) {
                  //require('toastr').info($filter('translate')('hpo.common.utilisercefilter'));
                  $rootScope.xgos.hpo.clauseWhere = undefined;
                  if (scope.map && scope.map.getView)
                    $rootScope.xgos.hpo.srid = scope.map
                      .getView()
                      .getProjection()
                      .getCode();
                }
                gaJsUtils.prepareThingsWhenNewSelection(
                  scope,
                  SelectManager,
                  res
                );
                SelectManager.addFeaturesFromGeojson(res.data);

                if (res.data.totalFeatures == 0) {
                  gclayers.clearhighLightFeatures();
                  SelectManager.clear();
                  require('toastr').error(
                    $filter('translate')('layermanager.no_selectable_layer')
                  );
                } else {
                  var newScope = $rootScope.$new();
                  newScope.map = scope.map;
                  newScope.panelsManager = scope.panelsManager;
                  if (pop) {
                    pop.close();
                  }
                  pop = gcPopup.open({
                    scope: newScope,
                    title: 'Informations : ',
                    content: '<div selectfeaturetreewidget></div>',
                    showClose: true,
                    resizable: true,
                    minimizeMaximize: true,
                    className: 'no-default-height',
                    minWidth: 430,
                    onclose: function() {
                      SelectManager.clear();
                    },
                  });
                  SelectManager.setpop(pop);
                }
              },
              function(result) {
                gcRestrictionProvider.showDetailsErrorMessage(result);
                if (SelectManager.getpop()) {
                  try {
                    if (SelectManager.getpop().element) {
                      SelectManager.getpop().destroy();
                    }
                    if (SelectManager.getpop().scope) {
                      SelectManager.getpop().scope.$broadcast('$destroy');
                    }
                  } catch (e) {
                    SelectManager.setpop(null);
                  }
                }
                gclayers.clearhighLightFeatures();
                SelectManager.clear();
              }
            );
          } else {
            require('toastr').error(
              $filter('translate')('layermanager.no_selectable_layer')
            );
          }
        });
      },
    };
  };

  toolbarselecttool.$inject = [
    '$http',
    'SelectManager',
    'gclayers',
    'gcPopup',
    '$filter',
    'gcRestrictionProvider',
    'gcInteractions',
    '$timeout',
    '$rootScope',
    'gaJsUtils',
    'PortalsFactory',
  ];
  return toolbarselecttool;
});
