'use strict';
define(function() {
  var setRuleHpoDiscretisation = function(
    AlertHpoFactory,
    FeatureTypeFactory,
    HpoCarteAppFactory,
    $window,
    ImportExportFactory,
    ngDialog,
    $q,
    $filter,
    $rootScope,
    $timeout,
    gaUrlUtils,
    ParametersFactory,
    ngTableParams,
    gaDomUtils,
    EditFactory,
    QueryFactory
  ) {
    return {
      templateUrl:
        'js/XG/widgets/hpoapp/home_admin_data/views/utilities/rules/set_rule_hpo_discretisation.html',
      restrict: 'EA',
      scope: {
        attr: '=',
        fti: '=',
        res: '=?',
        conditions: '=',
        usespecialfilters: '=?',
      },
      link: function(scope, elt, attrs, ctrl) {
        scope.conditions = angular.copy(scope.res) || {
          value: undefined,
          interpreteconditions: 'and',
          list: [],
        };
        scope.addCondition = function() {
          scope.conditions.list.push({});
        };
        scope.removeFromList = function(idx) {
          scope.idx = idx;
          var callback = function(isconfirm) {
            if (isconfirm) {
              scope.conditions.list.splice(scope.idx, 1);
              try {
                scope.$apply();
              } catch(err) {}
            }
            scope.idx = undefined;
          };
          var message = $filter('translate')(
            'hpo.data.prepare.correctiontools.correctallvalues.removeCondition'
          );
          AlertHpoFactory.alertConfirmCallback(
            $filter('translate')('hpo.common.warning'),
            message,
            'warning',
            true,
            undefined,
            '#F50072',
            true,
            undefined,
            undefined,
            true,
            true,
            callback
          );
        };

        scope.extractConditions = function() {
          if (
            scope.usespecialfilters &&
            scope.usespecialfilters.operands &&
            scope.usespecialfilters.operands.length > 0
          ) {
            scope.conditions.list = angular.copy(
              scope.usespecialfilters.operands
                .map(function(x) {
                  if (x.name === scope.attr.name) return x.operand;
                })
                .filter(function(x) {
                  if (x) return x;
                })
            );
            scope.conditions.interpreteconditions =
              scope.usespecialfilters.conditionattributes;
          }
        };
      },
    };
  };

  setRuleHpoDiscretisation.$inject = [
    'AlertHpoFactory',
    'FeatureTypeFactory',
    'HpoCarteAppFactory',
    '$window',
    'ImportExportFactory',
    'ngDialog',
    '$q',
    '$filter',
    '$rootScope',
    '$timeout',
    'gaUrlUtils',
    'ParametersFactory',
    'ngTableParams',
    'gaDomUtils',
    'EditFactory',
    'QueryFactory',
  ];
  return setRuleHpoDiscretisation;
});
