'use strict';
define(function() {
  var multicritereConstructionConfig = function(
    AlertHpoFactory,
    FeatureTypeFactory,
    HpoCarteAppFactory,
    $window,
    ImportExportFactory,
    ngDialog,
    $q,
    $filter,
    $rootScope,
    $timeout,
    gaUrlUtils,
    ParametersFactory,
    ngTableParams,
    gaDomUtils,
    EditFactory,
    QueryFactory,
    HpoAppServices,
    ngProgressFactory,
    $location,
    InitProvider,
    $interval,
    HpoMulticritereServices,
    HpoAppModelServices
  ) {
    return {
      templateUrl:
        'js/XG/widgets/hpoapp/analye_multicritere/views/directives/multicritere_parameters_config.html',
      restrict: 'EA',
      link: function(scope, elt, attrs, ctrl) {
        scope.lang = localStorage.getItem('current_language');
        /**
         * Template
         * @type {String}
         */
        scope.multicritereTemplate =
          'js/XG/widgets/hpoapp/analye_multicritere/views/templates/construction.tpl.html';

        /**
         * New element creation
         * @return {[type]} [description]
         */
        scope.initNewParam = function() {
          return {
            isNew: true,
            uid: HpoCarteAppFactory.getAppFactory().getRandomInteger(),
            label: 'hpo.multicritere.construct.new_criterea',
            name: undefined,
            type: scope.types[0].id,
            date: HpoCarteAppFactory.getAppFactory().formatDate(new Date()),
            fti: undefined,
            parameter: {},
            criterea: {},
            prevision: {},
            parameterInformations: {},
            critereaInformations: {},
            previsionInformations: {},
          };
        };

        /**
         * CRUD SERVICES
         * @type {[type]}
         */
        scope.getService = HpoMulticritereServices.getCritereas;
        scope.deleteService = HpoMulticritereServices.deleteCritereas;
        scope.saveService = HpoMulticritereServices.saveCriterea;

        /**
         * Widget config
         * @type {[type]}
         */
        scope.configName =
          HpoCarteAppFactory.getAppFactory().getAppname() +
          '_' +
          'HpoConstructCritereaConfig';
        scope.getReturnedTemplate = function(dataHpo) {
          if (dataHpo) {
            if (dataHpo.savedata.ftiuid) {
              var idx = scope.ftis
                .map(function(x) {
                  return x.uid;
                })
                .indexOf(dataHpo.savedata.ftiuid);
              if (~idx) {
                dataHpo.savedata.fti = scope.ftis[idx];
              } else {
                AlertHpoFactory.showAlertTemplateUpdate();
                dataHpo.savedata.fti = undefined;
                dataHpo.savedata.ftiuid = undefined;
              }
            } else if (dataHpo.savedata.fti) {
              var idx = scope.ftis
                .map(function(x) {
                  return x.uid;
                })
                .indexOf(dataHpo.savedata.fti.uid);
              if (~idx) {
                dataHpo.savedata.fti = scope.ftis[idx];
              } else {
                AlertHpoFactory.showAlertTemplateUpdate();
                dataHpo.savedata.fti = undefined;
                dataHpo.savedata.ftiuid = undefined;
              }
            }

            if (
              scope.currentParameter.isNew &&
              scope.currentParameter.uid !== dataHpo.savedata.uid
            ) {
              dataHpo.savedata.uid = HpoCarteAppFactory.getAppFactory().getRandomInteger();
              scope.oldParameter.uid = dataHpo.savedata.uid;
            } else {
              dataHpo.savedata.uid = scope.currentParameter.uid;
            }
            if (scope.currentParameter.isNew) {
              dataHpo.savedata.isNew = true;
              dataHpo.savedata.date = scope.currentParameter.date;
              delete dataHpo.savedata.id;
              delete scope.oldParameter.id;
            } else {
              dataHpo.savedata.id = scope.currentParameter.id;
            }
            if (scope.currentParameter.name)
              dataHpo.savedata.name = scope.currentParameter.name;
            if (scope.currentParameter.commentaire)
              dataHpo.savedata.commentaire = scope.currentParameter.commentaire;
            scope.currentParameter = angular.copy(dataHpo.savedata);
            scope.currentParameter.fti = dataHpo.savedata.fti;
          }
        };
        scope.disableButtons = function() {
          return !(
            scope.currentParameter &&
            (scope.currentParameter.hasOwnProperty('type') ||
              scope.currentParameter.isNew)
          );
        };

        scope.fti_component = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'critereas'
        )[0];
        scope.ftis = HpoCarteAppFactory.getAppFactory().getMulticritereFtis();
        scope.types = [
          {
            id: 'simple',
            label: $filter('translate')(
              'hpo.multicritere.construct.type.simple'
            ),
          },
        ];
        scope.keysToCheckOblig = ['name', 'type', 'categorie', 'fti'];
        scope.keysToCheckNotoblig = [
          'commentaire',
          'uid',
          'label',
          'isNew',
          'data',
          'columnDefs',
          'id',
          'date',
          'ftiuid',
          'parameter',
          'criterea',
          'prevision',
          'parameterInformations',
          'critereaInformations',
          'previsionInformations',
        ];

        scope.addTitle = 'hpo.multicritere.construct.add';
        scope.removeTitle = 'hpo.multicritere.construct.remove';
        scope.elementsNames = 'hpo.multicritere.construct.critereas';

        /**
         * Supplements
         * @type {Boolean}
         */
        scope.hasFti = true;
        scope.filterFunc = HpoCarteAppFactory.getAppFactory().filterFunc;

        scope.informations = {
          parameters: undefined,
        };

        var getAvailableCategories = function(parameters, uid, featid) {
          var categories = [];
          parameters.map(function(x) {
            if (
              !x.isNew &&
              x.categorie &&
              !~categories.indexOf(x.categorie) &&
              (!uid || x.uid !== uid) &&
              (!featid ||
                (x.ftiuid && x.ftiuid === featid) ||
                (x.fti && x.fti.uid === featid))
            )
              categories.push(x.categorie);
          });
          return categories;
        };

        var ftiparameters = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'parameters'
        )[0];
        HpoMulticritereServices.getParameters(ftiparameters.uid).then(
          function(res) {
            if (res && res.data) {
              scope.informations.parameters = res.data;
              scope.informations.categories = getAvailableCategories(
                scope.informations.parameters
              );
            }
          },
          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];
        var fti_filter = HpoCarteAppFactory.getAppFactory().getFeatureTypes(
          'amc_filter'
        )[0];
        var initialseFilter =function(fti){
          var filter = '"FTI_TABLE" = \'' + fti.uid + "'";
          var promise = QueryFactory.data(
            fti_filter.uid,
            filter,
            HpoCarteAppFactory.getAppFactory().getSrid(),
            '',
            '',
            ''
          );
          promise.then(
            function(res) {
              if (res && res.data && res.data.features.length > 0) {
                let filtredFeature = res.data.features.filter(feature => feature.properties.USED==true);
                 scope.clauseWhere = filtredFeature.length>0?filtredFeature[0].properties.FILTER:"1=1";
              }else{
                 scope.clauseWhere = "1=1";
              }
            },
            function(res) {
               scope.clauseWhere = "1=1";
            }
          );
        }
        scope.getAvailablePrevision = function(fti) {
          var where = '"FINALISER" = TRUE';
          if (scope.ftiprevision && scope.ftiprevision.uid) {
            HpoAppModelServices.getAvailablePrevions(
              fti.uid,
              scope.ftiprevision.uid,
              ftijeudonnee.uid,
              ftimodele.uid,
              where
            ).then(
              function(res) {
                if (res && res.data) {
                  scope.previsions = res.data.features;
                }
              },
              function(res) {
                AlertHpoFactory.showErrorMessage(res);
              }
            );
          }
        };
        scope.$watch('currentParameter.fti', function(newval, oldval) {
          if (newval && newval.uid) {
            scope.getAvailablePrevision(newval);
            initialseFilter(newval);
          }
        });

        scope.getCritereaInfo = function(criterea) {
          HpoMulticritereServices.getCritereas(
            scope.fti_component.uid,
            criterea.id
          ).then(
            function(res) {
              if (res && res.data) {
                scope.newCurrentParameter = res.data[0];
                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;
                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.previewExpression = function(currentParameter,forceCalculate) {
          if(currentParameter.isNew && !confirm($filter('translate')('hpo.common.previnormationmsg'))){
            return;
          }
          var analysis = {
            analysistool: 'calculatoranalysis',
            tableselected: currentParameter.fti,
            result: [],
            geoj: {},
            operands: [],
            attributestoselect: {},
            expression: currentParameter.data,
            interpreteattributes: 'and',
            interpreteconditions: 'and',
            selectedall: false,
            attributestouseindatatable: [],
            supplementAttributes: null,
            adminConfig: HpoCarteAppFactory.getInitProvider().getHpoConfig(),
            featid_parameters: ftiparameters.uid,
            featid_critereas: scope.fti_component.uid,
            featid_prevision: undefined,
            parameter: currentParameter.parameter,
            criterea: currentParameter.criterea,
            prevision: currentParameter.prevision,
            parameterInformations: currentParameter.parameterInformations,
            critereaInformations: currentParameter.critereaInformations,
            previsionInformations: currentParameter.previsionInformations,
            isNew : currentParameter.isNew,
            uidCriteria : currentParameter.uid,
            forceCalculate:forceCalculate,
            fti_component:scope.fti_component.uid,
            preview_source:"criterea",
            clauseWhere : scope.clauseWhere,
            checkClause : true,

          };
          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,
                  allresultserror: res.data.allresultserror,
                };
                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.showErrorMessage(res);
              }
              gaDomUtils.hideGlobalLoader();
            },
            function(res) {
              AlertHpoFactory.showErrorMessage(res);
              gaDomUtils.hideGlobalLoader();
            }
          );
        };

        scope.critereas = [];
        scope.advancedExpression = function(currentParameter) {
          HpoMulticritereServices.getCritereas(scope.fti_component.uid).then(
            function(res) {
              scope.isInit = true;
              gaDomUtils.hideGlobalLoader();
              if (res && res.data) {
                scope.currentParameter = currentParameter;
                scope.critereas = res.data;
                scope.informations.critereas_categories = getAvailableCategories(
                  scope.critereas,
                  currentParameter.uid,
                  currentParameter.fti.uid
                );
                scope.advanced = true;
                var diag = ngDialog.openConfirm({
                  template:
                    'js/XG/widgets/hpoapp/analye_multicritere/views/dialog/hpo.criterea.advanced.html',
                  className:
                    'ngdialog-theme-plain width1100 minheight500 nopadding miniclose',
                  closeByDocument: false,
                  scope: scope,
                });
                diag.then(
                  function(data) {
                    scope.advanced = false;
                    console.log(data);
                  },
                  function() {
                    scope.advanced = false;
                  }
                );
              }
            },
            function(res) {
              gaDomUtils.hideGlobalLoader();
              AlertHpoFactory.showErrorMessage(res);
            }
          );
        };

        var createExpression = function(v, type, id, currentParameter) {
          var sStart = $('.hpotextarea')[0].selectionStart;
          var sEnd = $('.hpotextarea')[0].selectionEnd;
          if (scope.currentParameter.data) {
            var beforelast = scope.currentParameter.data.charAt(sStart - 3);
            var last = scope.currentParameter.data.charAt(sStart - 2);
            if (last === ')' && beforelast !== "'") {
              if (
                scope.currentParameter.data.charAt(sStart - 3) === ',' &&
                scope.currentParameter.data.charAt(sStart - 4) === '('
              ) {
                var p = sStart - 3;
                scope.currentParameter.data =
                  scope.currentParameter.data.substring(0, p) +
                  v +
                  scope.currentParameter.data.substring(p);
              } else {
                var p = sStart - 2;
                scope.currentParameter.data =
                  scope.currentParameter.data.substring(0, p) +
                  v +
                  scope.currentParameter.data.substring(p);
              }
            } else {
              var firstPart = scope.currentParameter.data.substring(0, sStart);
              var endPart = scope.currentParameter.data.substring(
                sEnd,
                scope.currentParameter.data.length
              );
              scope.currentParameter.data = firstPart + v + endPart;
            }
          } else {
            var firstPart = scope.currentParameter.data.substring(0, sStart);
            var endPart = scope.currentParameter.data.substring(
              sEnd,
              scope.currentParameter.data.length
            );
            scope.currentParameter.data = firstPart + v + endPart;
          }
          if (typeof v === 'string')
            scope.currentParameter.data = scope.currentParameter.data + ' ';
          $('.hpotextarea')[0].select(scope.currentParameter.data.length - 1);
        };

        scope.editPrevision = function(obj) {
          if (obj && scope.ftiprevision && scope.ftiprevision.uid) {
            gaDomUtils.showGlobalLoader();
            HpoAppModelServices.getPrevision(
              scope.ftiprevision.uid,
              obj.properties.IDENTIFIANT,
              obj.properties.IDENTIFIANT_MODELE,
              obj.properties.IDENTIFIANT_CALAGE,
              ftijeudonnee.uid,
              ftimodele.uid,
              fticalage.uid
            ).then(
              function(res) {
                gaDomUtils.hideGlobalLoader();
                if (res && res.data) {
                  scope.newCurrentModel = res.data;
                  if(scope.hpoSimplifyVisualize){
                    scope.newCurrentModel.fti.attributes = scope.newCurrentModel.fti.attributes.filter(
                    function(x){
                      if(x.name.indexOf("_cox") == -1) return x
                    })
                  }
                  if (
                    scope.newCurrentModel &&
                    scope.newCurrentModel.status &&
                    scope.newCurrentModel.status !== 'FINISHED'
                  ) {
                    switch (scope.newCurrentModel.status) {
                      case 'FAILED':
                        scope.newCurrentModel.message =
                          $filter('translate')('hpo.model.calage.failed') +
                          ' ' +
                          scope.newCurrentModel.step +
                          '. ' +
                          $filter('translate')('hpo.model.calage.reason') +
                          ' ' +
                          scope.newCurrentModel.raison;
                        break;
                      case 'RUNNING':
                        scope.newCurrentModel.message = $filter('translate')(
                          'hpo.model.calage.running'
                        );
                        break;
                    }
                  } else {
                    scope.tableName = HpoCarteAppFactory.getAppFactory().getPrevisionTableName(
                      scope.newCurrentModel.identifiantcalage,
                      scope.newCurrentModel.identifiantprevision
                    );
                    scope.newCurrentModel.duree = HpoCarteAppFactory.getAppFactory().differenceDates(
                      scope.newCurrentModel.datestartsimulation,
                      scope.newCurrentModel.dateendsimulation
                    );
                  }
                  var dialog = ngDialog.open({
                    template:
                      'js/XG/widgets/hpoapp/model/views/dialog/hpo.model.prevision.info.html',
                    className:
                      'ngdialog-theme-plain width1100 nopadding miniclose',
                    scope: scope,
                  });
                }
              },
              function(res) {
                gaDomUtils.hideGlobalLoader();
                AlertHpoFactory.showErrorMessage(res);
              }
            );
          }
        };

        scope.addSupplementCriterea = function(
          val,
          type,
          id,
          currentParameter,
          casses,
          identifiant,
          fromCorrespondance
        ) {
          if (type === 'parameter' && val.type !== 'simple') {
            scope.expressions = {
              label: val.name,
              type: val.type,
              attributes: angular.copy(currentParameter.fti.attributes),
              header: undefined,
              column: undefined,
              header_param: undefined,
              column_param: undefined,
              selectedItemColumn: undefined,
              selectedItemHeader: undefined,
              header_source: 'attribute',
              column_source: 'attribute',
              colonnes: val.columnDefs,
            };
            var diag = ngDialog.openConfirm({
              template:
                'js/XG/widgets/hpoapp/analye_multicritere/views/dialog/hpo.criterea.choose_entete_column.html',
              className: 'ngdialog-theme-plain width800 nopadding miniclose',
              closeByDocument: false,
              scope: scope,
            });
            diag.then(function(data) {
              if (data) {
                currentParameter.parameterInformations[val.name] = {
                  header:
                    data.type === 'matrix'
                      ? (data.header_source==='criteria'?data.header:data.header.name)
                      : data.header_param.name,
                  column: data.column_source==='criteria'?data.column:data.column.name,
                  column_param: data.column_param.name,
                };
                var v = val.name;
                v = type + "('" + v + "')";
                if (
                  !currentParameter.hasOwnProperty(type) ||
                  !currentParameter[type]
                )
                  currentParameter[type] = {};
                currentParameter[type][val.uid] = val.name;
                createExpression(v, type, id, currentParameter);
              }
            });
          } else {
            if (type === 'prevision') {
              var v = val.NOM;
              v =
                type +
                "('" +
                v +
                "' , '" +
                identifiant.substring(0, 8) +
                "'  , '" +
                casses +
                "')";
              if (
                !currentParameter.hasOwnProperty(type) ||
                !currentParameter[type]
              )
                currentParameter[type] = {};
              currentParameter[type][val.IDENTIFIANT] = val;
            } else {
              var v = val.name;
              v = type + "('" + v + "')";
              if (
                !currentParameter.hasOwnProperty(type) ||
                !currentParameter[type]
              )
                currentParameter[type] = {};
              currentParameter[type][val.uid] = val.name;
            }
            if (angular.isDefined(fromCorrespondance)) {
              if (fromCorrespondance == 'column') {
                scope.expressions.column = v;
                scope.expressions.selectedItemColumn = val.name;
              } else {
                scope.expressions.header = v;
                scope.expressions.selectedItemHeader = val.name;
              }
            } else {
              createExpression(v, type, id, currentParameter);
            }
          }
        };
        scope.onChangeSourceMatrix = function(from) {
          if (from == 'column') {
            delete scope.expressions.column;
            delete scope.expressions.selectedItemColumn;
          } else {
            delete scope.expressions.header;
            delete scope.expressions.selectedItemHeader;
          }
        };

        scope.fonctions = scope.hpoSimplifyVisualize? [
         {
            id: 'rsf',
            label: 'IA HPO',
          },
        ] : [
          {
            id: 'cox',
            label: 'Cox PH',
          },
          {
            id: 'cox_survival',
            label: 'Cox Survival',
          },
          {
            id: 'rsf',
            label: 'IA HPO',
          },
        ];

        scope.infoParameter = function(currentParameter) {
          scope.newCurrentParameter = angular.copy(currentParameter);
          ngDialog.open({
            template:
              'js/XG/widgets/hpoapp/analye_multicritere/views/dialog/hpo.criterea.showParameter.html',
            className:
              'ngdialog-theme-plain width1100 minheight500 nopadding miniclose',
            closeByDocument: false,
            scope: scope,
          });
        };
      },
    };
  };

  multicritereConstructionConfig.$inject = [
    'AlertHpoFactory',
    'FeatureTypeFactory',
    'HpoCarteAppFactory',
    '$window',
    'ImportExportFactory',
    'ngDialog',
    '$q',
    '$filter',
    '$rootScope',
    '$timeout',
    'gaUrlUtils',
    'ParametersFactory',
    'ngTableParams',
    'gaDomUtils',
    'EditFactory',
    'QueryFactory',
    'HpoAppServices',
    'ngProgressFactory',
    '$location',
    'InitProvider',
    '$interval',
    'HpoMulticritereServices',
    'HpoAppModelServices',
  ];
  return multicritereConstructionConfig;
});
