'use strict';
define(function() {
  var statsAffaire = function(
    FeatureTypeFactory,
    $rootScope,
    ogcFactory,
    ChartsFactory,
    ngTableParams,
    chartFactory,
    $http,
    QueryFactory,
    gaDomUtils
  ) {
    return {
      templateUrl:
        'js/XG/widgets/utilities/statsAffaires/views/statsAffaire.html',
      restrict: 'A',

      link: function(scope, element, attrs, ctrl) {
        scope.globalType = [];
        scope.ftiuids = '';
        scope.resstats = [];
        scope.name_aliases = {};
        scope.conf = {
          showPerimeter: false,
          showArea: false,
        };

        scope.$watch('conf.res', function(newval) {
          if (newval) {
            if (
              scope.spatialClause &&
              scope.conf.componentChart &&
              scope.conf.componentChart.uid &&
              scope.conf.res &&
              scope.conf.res.name
            ) {
              if (scope.runningquery) {
                require('toastr').info(
                  'Traitement en cours. Veuillez attendre le résultat.'
                );
              } else {
                scope.runningquery = true;
                gaDomUtils.showFixedLocalLoader('.statistiques_affaires');
                /*QueryFactory.data(scope.conf.componentChart.uid, scope.spatialClause,
                                                scope.map.getView().getProjection().getCode() , undefined , undefined).then (function(resultdata){*/
                getFeaturesForChart();
                var chartoptions = chartFactory.getOptionsByType(
                  'pieChart',
                  [],
                  scope.conf.res.name
                );
                chartoptions.chart.width = 285;
                chartoptions.chart.height = 285;
                var chartConfig = {
                  source: {
                    fti: scope.conf.componentChart,
                    featureCollection: scope.resFeatureCollection,
                    selected: true,
                  },
                  cql_filter: {
                    attribute: {
                      x: {
                        name: scope.conf.res.name,
                      },
                    },
                    where: scope.spatialClause,
                    total: true,
                  },
                  options: chartoptions,
                  data: [],
                };
                var url = '/services/{portalid}/stats/charts/getChartData';
                $http
                  .post(url, chartConfig, {
                    timeout: 100000000000,
                  })
                  .then(
                    function(response) {
                      scope.conf.chartoptions = chartFactory.getOptionsByType(
                        'pieChart',
                        [],
                        scope.conf.res.name
                      );
                      scope.conf.chartoptions.chart.width = 285;
                      scope.conf.chartoptions.chart.height = 285;
                      scope.conf.chartdata = response.data.data;
                      scope.api.refresh();
                      gaDomUtils.removeLocalLoader('.statistiques_affaires');
                      scope.runningquery = false;
                    },
                    function() {
                      scope.runningquery = false;
                    }
                  );
              }
            }
          }
        });

        FeatureTypeFactory.get().then(function(res) {
          scope.componentftis = FeatureTypeFactory.resources.featuretypes
            .map(function(x) {
              if (x.geographic && x.published) {
                scope.name_aliases[x.name] = x.alias;
                return x;
              }
            })
            .filter(function(x) {
              if (x) return x;
            });
        });

        function getTypesComponent() {
          scope.ftiaffaireuids = scope.globalType
            .map(function(x) {
              return x.uid;
            })
            .join(',');
        }

        function getmapconfig() {
          var size = scope.map.getSize();
          var propmap = {};
          propmap.extent = scope.map.getView().calculateExtent(size);
          propmap.zoom = scope.map.getView().getZoom();
          propmap.srid = scope.map
            .getView()
            .getProjection()
            .getCode();

          return propmap;
        }

        function getFeaturesForChart() {
          scope.resFeatureCollection = angular.copy(scope.resstatsfeature);
          scope.resFeatureCollection.features = angular.copy(
            scope.resstatsfeature.features
              .map(function(f) {
                if (f.id.split('.')[0] === scope.conf.componentChart.name)
                  return f;
              })
              .filter(function(f) {
                if (f) return f;
              })
          );
        }

        scope.runningquery = false;
        var GetStatsForAffaires = function() {
          if (scope.runningquery) {
            require('toastr').info(
              'Traitement en cours. Veuillez attendre le résultat.'
            );
          } else {
            var propmap = getmapconfig();
            var extent = propmap.extent;

            var leftX = extent[0];
            var bottomY = extent[1];

            var rightX = extent[2];
            var topY = extent[3];
            scope.runningquery = true;
            gaDomUtils.showFixedLocalLoader('.statistiques_affaires');
            scope.spatialClause =
              'INTERSECTS(geom, POLYGON((' +
              leftX +
              ' ' +
              bottomY +
              ',' +
              rightX +
              ' ' +
              bottomY +
              ',' +
              rightX +
              ' ' +
              topY +
              ',' +
              leftX +
              ' ' +
              topY +
              ',' +
              leftX +
              ' ' +
              bottomY +
              ')))';

            var promise = ogcFactory.getfeatures(
              'GetFeature',
              'WFS',
              '1.0.0',
              scope.ftiaffaireuids,
              'json',
              scope.map
                .getView()
                .getProjection()
                .getCode(),
              scope.spatialClause
            );
            promise.then(
              function(result) {
                scope.resstatsfeature = result.data;
                ChartsFactory.datastats(scope.resstatsfeature).then(
                  function(res) {
                    scope.resstats = res.data;
                    if (
                      scope.spatialClause &&
                      scope.conf.componentChart &&
                      scope.conf.componentChart.uid &&
                      scope.conf.res &&
                      scope.conf.res.name
                    ) {
                      /*QueryFactory.data(scope.conf.componentChart.uid, scope.spatialClause,
                                                scope.map.getView().getProjection().getCode() , undefined , undefined).then (function(resultdata){*/
                      getFeaturesForChart();
                      var chartoptions = chartFactory.getOptionsByType(
                        'pieChart',
                        [],
                        scope.conf.res.name
                      );
                      chartoptions.chart.width = 285;
                      chartoptions.chart.height = 285;
                      var chartConfig = {
                        source: {
                          fti: scope.conf.componentChart,
                          featureCollection: scope.resFeatureCollection,
                          selected: true,
                        },
                        cql_filter: {
                          attribute: {
                            x: {
                              name: scope.conf.res.name,
                            },
                          },
                          where: scope.spatialClause,
                          total: true,
                        },
                        options: chartoptions,
                        data: [],
                      };
                      var url =
                        '/services/{portalid}/stats/charts/getChartData';
                      $http
                        .post(url, chartConfig, {
                          timeout: 100000000000,
                        })
                        .then(function(response) {
                          scope.conf.chartoptions = chartFactory.getOptionsByType(
                            'pieChart',
                            [],
                            scope.conf.res.name
                          );
                          scope.conf.chartoptions.chart.width = 285;
                          scope.conf.chartoptions.chart.height = 285;
                          //scope.conf.chartoptions = response.data.options;
                          scope.conf.chartdata = response.data.data;
                          scope.api.refresh();
                          gaDomUtils.removeLocalLoader(
                            '.statistiques_affaires'
                          );
                          scope.runningquery = false;
                        });
                    } else {
                      gaDomUtils.removeLocalLoader('.statistiques_affaires');
                      scope.runningquery = false;
                    }
                    scope.tableParamsParameters.reload();
                  },
                  function() {
                    console.error('calcul stats');
                    scope.runningquery = false;
                  }
                );
              },
              function() {
                console.error('calcul stats');
                scope.runningquery = false;
              }
            );
          }
        };

        scope.addGlobalType = function(selectGlobal) {
          if (selectGlobal && scope.globalType.indexOf(selectGlobal) === -1)
            scope.globalType.push(selectGlobal);
          getTypesComponent();
          $rootScope.$broadcast('init_update_chart_affaire');
        };

        scope.removeAllTypes = function() {
          scope.globalType = [];
          getTypesComponent();
          $rootScope.$broadcast('init_update_chart_affaire');
        };

        scope.removeGlobalType = function(idx) {
          scope.globalType.splice(idx, 1);
          getTypesComponent();
          $rootScope.$broadcast('init_update_chart_affaire');
        };

        scope.visible = false;
        scope.showStats = function() {
          scope.visible = !scope.visible;
          if (scope.visible) GetStatsForAffaires();
        };

        scope.tableParamsParameters = new ngTableParams(
          {
            page: 1, // show first page
            count: 10, // count per page
          },
          {
            total: 0, // length of data
            getData: function($defer, params) {
              var displayedTab = scope.resstats.slice(
                (params.page() - 1) * params.count(),
                params.page() * params.count()
              );

              params.total(scope.resstats.length); // set total for recalc pagination

              $defer.resolve(displayedTab);
            },
          }
        );

        scope.$on('init_update_chart_affaire', function(event, arg) {
          if ($rootScope.xgos.portal.name === 'AFFAIRES' && scope.visible)
            GetStatsForAffaires();
        });

        var btnElt = $(element.children()[0]);
        btnElt.bind('click', function() {
          if (scope.isActive) {
            btnElt.removeClass('btn-info');
            btnElt.addClass('btn-default');
            scope.isActive = false;
          } else {
            btnElt.removeClass('btn-default');
            btnElt.addClass('btn-info');
            scope.isActive = true;
          }
        });

        scope.$on('closeToolsBar_statsaffairefilter', function() {
          if (scope.isActive) $('#toolbar_statsaffairefilter_popover').click();
          btnElt.removeClass('btn-info');
          btnElt.addClass('btn-default');
          scope.isActive = false;
        });
      },
    };
  };

  statsAffaire.$inject = [
    'FeatureTypeFactory',
    '$rootScope',
    'ogcFactory',
    'ChartsFactory',
    'ngTableParams',
    'chartFactory',
    '$http',
    'QueryFactory',
    'gaDomUtils',
  ];
  return statsAffaire;
});
