'use strict';
define(function() {
  var basemapwidget = function(
    gcPropertiesLayers,
    gclayers,
    ParametersFactory,
    gcPopup,
    extendedNgDialog,
    gaDomUtils,
    GeoTreatmentFactory
  ) {
    return {
      templateUrl:
        'js/XG/widgets/mapapp/geotreatment/views/treatments/treatGenerateNode.html',
      restrict: 'A',
      link: function(scope, elt, attrs, ctrl) {
        var map = scope.map;
        scope.activetreatment = '';
        scope.res = {};
        scope.attributes_select = [];
        scope.inprogress = false;
        scope.interrupt = false;
        scope.geoLimit = GeoTreatmentFactory.DATABASE;

        let handlePromiseError= () =>{
          scope.inprogress = false;
        };

        scope.stop = function() {
          GeoTreatmentFactory.stoptreatment(scope.state).then(function(data) {
            scope.inprogress = false;
            scope.interrupt = true;
          }).catch(handlePromiseError);
        };

        scope.vopenResult = function() {
          scope.geoj = scope.result;
          if (scope.panelsManager){
            scope.panelsManager.removePanel('selecttab');
          }
          scope.panelsManager.addPanel({
            id: 'selecttab',
            stickToRight: true,
            templateUrl:
              'js/XG/widgets/mapapp/geotreatment/views/panels/panel.datatable.html',
            scope: scope,
            stickToBorder: true,
            visible: true,
          });
        };

        scope.run = function(fti1) {
          scope.inprogress = true;
          const featureCollections = [];
          const spatialClause = 
            GeoTreatmentFactory.getSpatialClause(
              scope.geoLimit,
              scope.map,
              scope.limitZoneGeometry,
              [fti1.name],
              featureCollections);
          var param = {
            spatialclause: spatialClause,
            featureCollections: featureCollections,
            fti1: fti1.uid,
            fti2: fti1.uid,
            srid: scope.map.getView().getProjection().getCode()
          };
         GeoTreatmentFactory.treatment(
            param,
            'GenerateNode'
          )
         .then(function(data) {
            scope.state = data.data;
           scope.httpStatus=data.status;
            var actionList = [
              {
                execute: function(obj) {
                  scope.correction(obj);
                },
                icon: 'glyphicon glyphicon-cog',
              },
            ];
            GeoTreatmentFactory.tick(scope, ['line1', 'line2'], actionList);
          }).catch(handlePromiseError);
        };
      },
    };
  };

  basemapwidget.$inject = [
    'gcPropertiesLayers',
    'gclayers',
    'ParametersFactory',
    'gcPopup',
    'extendedNgDialog',
    'gaDomUtils',
    'GeoTreatmentFactory',
  ];
  return basemapwidget;
});
