'use strict';
define(function() {
  var formSpecialHpo = function(
    $http,
    gclayers,
    gcStyleFactory,
    FeatureTypeFactory,
    GeometryFactory,
    gcInteractions,
    HpoCarteAppFactory,
    $rootScope,
    $filter,
    QueryFactory,
    InitProvider,
    HpoMulticritereServices,
    ngDialog,
    AlertHpoFactory,
    gaDomUtils,
    HpoAppServices
  ) {
    return {
      templateUrl:
        'js/XG/widgets/hpoapp/chantiers/views/directives/form_special_hpo.html',
      restrict: 'A',
      scope: {
        map: '=map',
        result: '=res',
        field: '=',
        templatefields: '=?',
        toolBarWidget: '=?toolbarwidget',
        currentobj: '=?currentobj',
        onfinish: '&',
      },
      link: function(scope, element, attrs, ctrl) {
        scope.ftiChantiers = FeatureTypeFactory.getFeatureByUid(
          scope.field.config.ftid
        );
        if (
          scope.field.config.attribute &&
          scope.field.config.attribute.name &&
          scope.ftiChantiers
        ) {
          var idx = scope.ftiChantiers.attributes
            .map(function(x) {
              return x.name;
            })
            .indexOf(scope.field.config.attribute.name);
          if (~idx)
            scope.field.config.attribute = scope.ftiChantiers.attributes[idx];
        }

        scope.getAvailableCritereas = function(ftid) {
          var filter = '"FEATID" = \'' + ftid + "'";
          QueryFactory.data(
            scope.ftiCritereas.uid,
            filter,
            HpoCarteAppFactory.getAppFactory().getSrid(),
            '',
            '',
            ''
          ).then(
            function(res) {
              if (res && res.data) {
                scope.availableCritereas = res.data.features;
              }
            },
            function(res) {
              AlertHpoFactory.showErrorMessage(res);
            }
          );
        };

        var initDirective = function() {
          scope.availableCritereas = [];
          scope.ftiParameters = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
            'parameters'
          )[0];
          scope.ftiCritereas = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
            'critereas'
          )[0];
          if (
            scope.currentobj &&
            scope.currentobj.current &&
            scope.currentobj.current.properties &&
            scope.currentobj.current.properties.FTIUID
          ) {
            scope.getAvailableCritereas(
              scope.currentobj.current.properties.FTIUID
            );
          }
        };

        if (!HpoCarteAppFactory.getAppFactory().isAppInitiated()) {
          HpoCarteAppFactory.getInitProvider()
            .initialiseApplication()
            .then(function() {
              HpoCarteAppFactory.getAppFactory().initFactory(
                scope.ftiChantiers.storeName
              );
              initDirective();
            });
        } else {
          HpoCarteAppFactory.getAppFactory().initFactory(
            scope.ftiChantiers.storeName
          );
          initDirective();
        }

        scope.$watch('currentobj.current.properties.FTIUID', function(newval) {
          if (newval) scope.getAvailableCritereas(newval);
        });

        scope.getCritereaInfo = function(criterea) {
          HpoMulticritereServices.getCritereas(
            scope.ftiCritereas.uid,
            criterea.id
          ).then(
            function(res) {
              if (res && res.data) {
                scope.newCurrentParameter = res.data[0];
                scope.ftis = HpoCarteAppFactory.getAppFactory().getMulticritereFtis();
                if (scope.newCurrentParameter.ftiuid) {
                  var idx = scope.ftis
                    .map(function(x) {
                      return x.uid;
                    })
                    .indexOf(scope.newCurrentParameter.ftiuid);
                  if (~idx) scope.newCurrentParameter.fti = scope.ftis[idx];
                }
                scope.readonly = true;

                scope.filterFunc = HpoCarteAppFactory.getAppFactory().filterFunc;
                ngDialog.open({
                  template:
                    'js/XG/widgets/hpoapp/analye_multicritere/views/dialog/hpo.preview.tpl.html',
                  className:
                    'ngdialog-theme-plain width1100 minheight500 nopadding miniclose',
                  closeByDocument: false,
                  scope: scope,
                });
              }
            },
            function(res) {
              AlertHpoFactory.showErrorMessage(res);
            }
          );
        };

        scope.ftiprevision = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'prevision'
        )[0];
        var ftijeudonnee = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'jeu_de_donnee'
        )[0];
        var fticalage = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'calage'
        )[0];
        var ftimodele = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'modal_historic'
        )[0];
        scope.previewExpression = function(currentParameter) {
          var ids = scope.currentobj.canalisations_liees
            .map(function(x) {
              return x.id;
            })
            .join("','");
          var analysis = {
            analysistool: 'calculatoranalysis',
            tableselected: currentParameter.fti,
            result: [],
            geoj: {},
            operands: [],
            clauseWhere: " IN ('" + ids + "')",
            checkClause: true,
            attributestoselect: {},
            expression: currentParameter.data,
            interpreteattributes: 'and',
            interpreteconditions: 'and',
            selectedall: false,
            attributestouseindatatable: [],
            supplementAttributes: null,
            adminConfig: HpoCarteAppFactory.getInitProvider().getHpoConfig(),
            featid_parameters: scope.ftiParameters.uid,
            featid_critereas: scope.ftiCritereas.uid,
            featid_prevision: undefined,
            parameter: currentParameter.parameter,
            criterea: currentParameter.criterea,
            prevision: currentParameter.prevision,
            parameterInformations: currentParameter.parameterInformations,
            critereaInformations: currentParameter.critereaInformations,
            previsionInformations: currentParameter.previsionInformations,
          };
          if (scope.ftiprevision && scope.ftiprevision.uid) {
            analysis.featid_prevision = scope.ftiprevision.uid;
          }
          gaDomUtils.showGlobalLoader();
          HpoAppServices.analyseData(analysis).then(
            function(res) {
              if (res.data && res.data.status && res.data.result) {
                scope.result = {
                  geoj: res.data.result,
                  supplementAttributes: [
                    HpoCarteAppFactory.getAppFactory().getCalcAttribute(),
                  ],
                  fti: currentParameter.fti,
                  attributes: HpoCarteAppFactory.getAppFactory().getAttributesWithFilter(currentParameter.fti.attributes),
                  expression: currentParameter.data,
                };
                try {
                  if (
                    scope.result.geoj &&
                    scope.result.geoj.features &&
                    scope.result.geoj.features.length === 0
                  ) {
                    AlertHpoFactory.getSimpleSuccess(
                      $filter('translate')('hpo.common.success'),
                      $filter('translate')(
                        'hpo.data.prepare.analysissuccessbutnodata'
                      ),
                      true,
                      'info'
                    );
                  } else {
                    ngDialog.open({
                      template:
                        'js/XG/widgets/hpoapp/analye_multicritere/views/dialog/hpo.criterea.preview.html',
                      className:
                        'ngdialog-theme-plain width1100 minheight500 nopadding miniclose',
                      closeByDocument: false,
                      scope: scope,
                    });
                  }
                } catch (e) {
                  console.error(e.stack);
                }
              } else {
                AlertHpoFactory.getSimpleSuccess(
                  $filter('translate')('hpo.data.prepare.succes'),
                  $filter('translate')('hpo.data.prepare.analysissuccess'),
                  false
                );
              }
              gaDomUtils.hideGlobalLoader();
            },
            function(res) {
              AlertHpoFactory.showErrorMessage(res);
              gaDomUtils.hideGlobalLoader();
            }
          );
        };
      },
    };
  };

  formSpecialHpo.$inject = [
    '$http',
    'gclayers',
    'gcStyleFactory',
    'FeatureTypeFactory',
    'GeometryFactory',
    'gcInteractions',
    'HpoCarteAppFactory',
    '$rootScope',
    '$filter',
    'QueryFactory',
    'InitProvider',
    'HpoMulticritereServices',
    'ngDialog',
    'AlertHpoFactory',
    'gaDomUtils',
    'HpoAppServices',
  ];
  return formSpecialHpo;
});
