'use strict';
define(function() {
  var multicritereParameterMatrix = function(
    AlertHpoFactory,
    FeatureTypeFactory,
    HpoCarteAppFactory,
    $window,
    ImportExportFactory,
    ngDialog,
    $q,
    $filter,
    $rootScope,
    $timeout,
    gaUrlUtils,
    ParametersFactory,
    ngTableParams,
    gaDomUtils,
    EditFactory,
    QueryFactory,
    HpoAppServices,
    ngProgressFactory,
    $location,
    InitProvider,
    $interval,
    uiGridConstants
  ) {
    return {
      templateUrl:
        'js/XG/widgets/hpoapp/analye_multicritere/views/directives/multicritere_parameter_matrix.html',
      restrict: 'EA',
      scope: {
        data: '=?',
        type: '=?',
        columnDefs: '=?',
      },
      link: function(scope, elt, attrs, ctrl) {
        scope.lang = localStorage.getItem('current_language');

        scope.singleFilter = function(renderableRows) {
          if (scope.filterValue) {
            var matcher = new RegExp(scope.filterValue);
            renderableRows.forEach(function(row) {
              var match = false;
              scope.gridHpo.columnDefs
                .map(function(x) {
                  return x.name;
                })
                .forEach(function(field) {
                  if (
                    !scope.filterValue ||
                    row.entity[field].score(scope.filterValue) > 0.3
                  ) {
                    match = true;
                  }
                });
              if (!match) {
                row.visible = false;
              }
            });
          }
          return renderableRows;
        };

        scope.keyDownFilter = function($event, empty) {
          if (!empty) {
            if ($event.keyCode === 27) {
              scope.filterValue = '';
              scope.filter();
            }
          } else {
            scope.filterValue = '';
            scope.filter();
          }
        };

        scope.filter = function() {
          scope.gridApi.grid.refresh();
        };

        scope.data = scope.data || [];
        scope.columnDefs = scope.columnDefs || [];

        scope.gridHpo = {
          enableGridMenu: true,
          enableFiltering: false,
          exporterMenuCsv: true,
          exporterMenuExcel: false,
          exporterMenuPdf: false,
          enableSelectAll: true,
          multiSelect: true,
          enableFullRowSelection: true,
          enableRowSelection: true,
          exporterCsvFilename: scope.data.name
            ? scope.data.name
            : 'download.csv',
          paginationPageSizes: [25, 50, 75, 100, 200, 500, 1000],
          paginationPageSize: 25,
          // modifierKeysToMultiSelectCells: true,
          // keyDownOverrides: [{ keyCode: 39, ctrlKey: true }],
          importerDataAddCallback: function(grid, newObjects) {
            scope.gridHpo.data = scope.gridHpo.data.concat(newObjects);
          },
          // showGridFooter: true,
          onRegisterApi: function(gridApi) {
            scope.gridApi = gridApi;
            scope.gridApi.grid.registerRowsProcessor(scope.singleFilter, 200);
            // var cellTemplate = 'ui-grid/selectionRowHeader';   // you could use your own template here
            // scope.gridApi.core.addRowHeaderColumn( { name: 'rowHeaderCol', displayName: 'added column',
            //                     cellTemplate: cellTemplate } );
          },
          columnDefs: scope.columnDefs,
          data: scope.data,
        };

        var addData = function(data) {
          try {
            if (data.exists_data) {
              if (data.choice === 'add')
                scope.gridHpo.data = scope.gridHpo.data.concat(scope.jstext);
              else {
                scope.gridHpo.data = scope.jstext;
              }
            } else {
              scope.gridHpo.data = scope.jstext;
            }
            if (scope.gridHpo.data.length >= 0) {
              scope.gridHpo.columnDefs = [];
              var existingNames = scope.gridHpo.columnDefs.map(function(x) {
                return x.name;
              });
              Object.keys(scope.jstext[0]).map(function(x) {
                if (x !== '$$hashKey' && existingNames.indexOf(x) === -1)
                  checkOrAddColumnDef(x, x);
              });
            }
            scope.pastedText = undefined;
            scope.columnDefs = scope.gridHpo.columnDefs;
            scope.data = scope.gridHpo.data;
            // scope.$apply();
            AlertHpoFactory.successAdd();
          } catch (e) {
            AlertHpoFactory.showErrorMessage(e);
          }
        };

        scope.pastedText = undefined;
        scope.pastedTextArea = function(event) {
          setTimeout(function() {
            try {
              scope.jstext = HpoCarteAppFactory.getAppFactory().csvJSON(
                scope.pastedText,
                '	'
              );
              scope.newGridHpo = {
                paginationPageSizes: [25, 50, 75, 100, 200, 500, 1000],
                paginationPageSize: 25,
                data: scope.jstext,
              };
              scope.newInformations = {
                grid: scope.newGridHpo,
                text: scope.jstext,
                exists_data: scope.gridHpo.data.length > 0,
              };
              if (scope.gridHpo.data.length > 0)
                scope.newInformations.choice = 'replace';
              var dialog = ngDialog.openConfirm({
                template:
                  'js/XG/widgets/hpoapp/analye_multicritere/views/dialog/hpo.multicritere.parameters.paste.html',
                className:
                  'ngdialog-theme-plain width800 minheight500 nopadding miniclose',
                closeByDocument: false,
                scope: scope,
              });
              dialog.then(function(data) {
                addData(data);
              });
            } catch (e) {
              AlertHpoFactory.showErrorMessage(e);
            }
          }, 300);
        };

        scope.lengthObjectTrue = function(obj) {
          var el = Object.keys(obj)
            .map(function(x) {
              if (obj[x]) return x;
            })
            .filter(function(x) {
              if (x) return x;
            });
          return el.length;
        };

        scope.toggleFilter = function() {
          scope.gridHpo.enableFiltering = !scope.gridHpo.enableFiltering;
          scope.gridHpo.columnDefs.map(function(x) {
            x.enableFiltering = scope.gridHpo.enableFiltering;
          });
          scope.gridApi.core.notifyDataChange(uiGridConstants.dataChange.ALL);
          if (scope.gridHpo.enableFiltering) {
            $('.ui-grid-header-cell')
              .css('height', '60px')
              .css('min-height', '60px');
          } else {
            $('.ui-grid-header-cell')
              .css('height', '30px')
              .css('min-height', '30px');
          }
        };

        scope.columnDelimiter = ',';
        var exportcsvdialog;
        scope.showConfigSparator = function() {
          exportcsvdialog = ngDialog.openConfirm({
            template:
              'js/XG/widgets/hpoapp/analye_multicritere/views/dialog/csvFormatPrompt.html',
            className: 'ngdialog-theme-plain nopadding miniclose',
            scope: scope,
            showClose: true,
          });
          exportcsvdialog.then(function(data) {
            scope.columnDelimiter = data;
          });
        };

        var reader = new FileReader(),
          blob,
          file;
        scope.loadCsvFile = function(input) {
          try {
            file = input.files[0];
            // csv only
            if (!~file.name.indexOf('.csv')) {
              require('toastr').error(
                $filter('translate')('csvgeocoder.csv_only')
              );
              return;
            }
            if (file.size >= 5000000) {
              require('toastr').error(
                $filter('translate')('csvgeocoder.file_too_heavy')
              );
              return;
            }

            reader.readAsText(file, 'utf-8');

            reader.onload = function(e) {
              try {
                scope.$apply(function() {
                  blob = new Blob([reader.result], {
                    type: 'text/csv; charset=utf-8',
                  });
                  scope.currentFileName = file.name;
  
                  try {
                    scope.csvData = scope.jstext = HpoCarteAppFactory.getAppFactory().csvJSON(
                      reader.result,
                      scope.columnDelimiter
                    );
                    scope.newGridHpo = {
                      paginationPageSizes: [25, 50, 75, 100, 200, 500, 1000],
                      paginationPageSize: 25,
                      data: scope.jstext,
                    };
                    scope.newInformations = {
                      grid: scope.newGridHpo,
                      text: scope.jstext,
                      exists_data: scope.gridHpo.data.length > 0,
                    };
                    if (scope.gridHpo.data.length > 0)
                      scope.newInformations.choice = 'replace';
                    var dialog = ngDialog.openConfirm({
                      template:
                        'js/XG/widgets/hpoapp/analye_multicritere/views/dialog/hpo.multicritere.parameters.paste.html',
                      className:
                        'ngdialog-theme-plain width800 minheight500 nopadding miniclose',
                      closeByDocument: false,
                      scope: scope,
                    });
                    dialog.then(function(data) {
                      addData(data);
                    });
                  } catch (e) {
                    AlertHpoFactory.showErrorMessage(e);
                  }
                });
              } catch(err) {}
            };
          } catch (e) {
            AlertHpoFactory.showErrorMessage(e);
          }
        };

        scope.updateMultiple = function() {
          scope.result = scope.gridApi.selection.getSelectedRows();
          scope.existingvalues = {
            properties: {},
            existingvalues: {},
            modified: {},
            keys: [],
            types: {},
          };
          var names = scope.gridHpo.columnDefs.map(function(x) {
            return x.name;
          });
          scope.result.map(function(x) {
            if (x) {
              for (var i = 0; i < names.length; i++) {
                var key = names[i];
                if (key && key !== '$$hashKey') {
                  if (scope.existingvalues.existingvalues.hasOwnProperty(key)) {
                    if (
                      !~scope.existingvalues.existingvalues[key].indexOf(x[key])
                    )
                      scope.existingvalues.existingvalues[key].push(x[key]);
                    if (!~scope.existingvalues.keys.indexOf(key)) {
                      scope.existingvalues.keys.push(key);
                      scope.existingvalues.types[key] = typeof x[key];
                    }
                  } else {
                    scope.existingvalues.existingvalues[key] = [];
                    if (
                      !~scope.existingvalues.existingvalues[key].indexOf(x[key])
                    )
                      scope.existingvalues.existingvalues[key].push(x[key]);
                    scope.existingvalues.modified[key] = false;
                    scope.existingvalues.properties[key] = undefined;
                    if (!~scope.existingvalues.keys.indexOf(key)) {
                      scope.existingvalues.keys.push(key);
                      scope.existingvalues.types[key] = typeof x[key];
                    }
                  }
                }
              }
            }
          });
          var dialog = ngDialog.openConfirm({
            template:
              'js/XG/widgets/hpoapp/analye_multicritere/views/dialog/hpo.updateMultiple.html',
            className: 'ngdialog-theme-plain width800 nopadding miniclose',
            scope: scope,
          });
          dialog.then(function(data) {
            scope.result.map(function(x) {
              if (x) {
                for (var key in data.properties) {
                  if (
                    key &&
                    data.modified &&
                    data.modified.hasOwnProperty(key) &&
                    data.modified[key]
                  ) {
                    x[key] = data.properties[key];
                  }
                }
              }
            });
            scope.data = scope.gridHpo.data;
            scope.columnDefs = scope.gridHpo.columnDefs;
            scope.gridApi.core.notifyDataChange(uiGridConstants.dataChange.ALL);
            AlertHpoFactory.successUpdate();
          });
        };

        scope.updateHeader = function() {
          scope.existingvalues = [];
          var names = scope.gridHpo.columnDefs.map(function(x) {
            scope.existingvalues.push({
              name: x.name,
              label: x.displayName,
              value: undefined,
              modified: false,
            });
          });
          var dialog = ngDialog.openConfirm({
            template:
              'js/XG/widgets/hpoapp/analye_multicritere/views/dialog/hpo.updateHeader.html',
            className: 'ngdialog-theme-plain width800 nopadding miniclose',
            scope: scope,
          });
          dialog.then(function(data) {
            try {
              if (data) {
                var names = scope.gridHpo.columnDefs.map(function(x) {
                  return x.name;
                });
                data.map(function(columnDef) {
                  if (
                    columnDef &&
                    columnDef.modified &&
                    angular.isDefined(columnDef.value)
                  ) {
                    var idx = names.indexOf(columnDef.name);
                    if (~idx) {
                      var columnDefExi = angular.copy(
                        scope.gridHpo.columnDefs[idx]
                      );
                      columnDefExi.name = columnDef.value;
                      columnDefExi.displayName = columnDef.value;
                      scope.gridHpo.columnDefs.splice(idx, 1);
                      scope.gridHpo.columnDefs.splice(idx, 0, columnDefExi);
                      scope.gridHpo.data.map(function(x) {
                        if (x && x.hasOwnProperty(columnDef.name)) {
                          x[columnDef.value] = x[columnDef.name];
                          delete x[columnDef.name];
                        }
                      });
                    }
                  }
                });
              }
              scope.data = scope.gridHpo.data;
              scope.columnDefs = scope.gridHpo.columnDefs;
              scope.gridApi.core.notifyDataChange(
                uiGridConstants.dataChange.ALL
              );
              AlertHpoFactory.successUpdate();
            } catch (e) {
              AlertHpoFactory.showErrorMessage(e);
            }
          });
        };

        var checkOrAddColumnDef = function(name, displayName) {
          var names = scope.gridHpo.columnDefs.map(function(x) {
            return x.name;
          });
          var idx = names.indexOf(name);
          if (~idx) {
            var columnDefExi = angular.copy(scope.gridHpo.columnDefs[idx]);
            columnDefExi.name = name;
            columnDefExi.displayName = displayName;
            scope.gridHpo.columnDefs.splice(idx, 1);
            scope.gridHpo.columnDefs.splice(idx, 0, columnDefExi);
          } else {
            scope.gridHpo.columnDefs.push({
              name: name,
              displayName: displayName,
              headerTooltip: true,
              cellTooltip: true,
              enableCellEdit: true,
              enableFiltering: scope.gridHpo.enableFiltering,
            });
          }
        };

        scope.addColumn = function() {
          scope.colonne = {
            existingNames: scope.gridHpo.columnDefs.map(function(x) {
              return x.name;
            }),
          };
          var dialog = ngDialog.openConfirm({
            template:
              'js/XG/widgets/hpoapp/analye_multicritere/views/dialog/hpo.addcolonne.html',
            className: 'ngdialog-theme-plain width800 nopadding miniclose',
            scope: scope,
          });
          dialog.then(function(data) {
            if (data && data.name) {
              checkOrAddColumnDef(data.name, data.name);
              scope.data = scope.gridHpo.data;
              scope.columnDefs = scope.gridHpo.columnDefs;
              scope.gridApi.core.notifyDataChange(
                uiGridConstants.dataChange.ALL
              );
              AlertHpoFactory.successUpdate();
            }
          });
        };

        scope.addLine = function() {
          var obj = {};
          scope.gridHpo.columnDefs.map(function(x) {
            obj[x.name] = undefined;
          });
          scope.gridHpo.data.push(obj);
          scope.data = scope.gridHpo.data;
          scope.columnDefs = scope.gridHpo.columnDefs;
          scope.gridApi.core.notifyDataChange(uiGridConstants.dataChange.ALL);
          AlertHpoFactory.successAdd();
        };

        scope.removeLine = function() {
          var result = scope.gridApi.selection.getSelectedRows();
          var callback = function(isconfirm) {
            if (isconfirm) {
              var names = scope.gridHpo.columnDefs.map(function(x) {
                return x.name;
              });
              for (var i = 0; i < result.length; i++) {
                var idx = scope.gridHpo.data.indexOf(result[i]);
                if (~idx) scope.gridHpo.data.splice(idx, 1);
              }
              scope.data = scope.gridHpo.data;
              scope.columnDefs = scope.gridHpo.columnDefs;
              scope.gridApi.core.notifyDataChange(
                uiGridConstants.dataChange.ALL
              );
              AlertHpoFactory.successDelete();
              try {
                scope.$apply();
              } catch(err) {}
            }
          };
          var message =
            $filter('translate')('hpo.multicritere.parameters.removeline') +
            '. ' +
            $filter('translate')('hpo.common.sur');
          AlertHpoFactory.alertConfirmCallback(
            $filter('translate')('hpo.common.warning'),
            message,
            'warning',
            true,
            undefined,
            '#F50072',
            true,
            undefined,
            undefined,
            true,
            true,
            callback
          );
        };

        scope.removeColumn = function() {
          scope.colonne = {
            existingNames: [],
            list: {},
          };
          scope.colonne.existingNames = scope.gridHpo.columnDefs.map(function(
            x
          ) {
            scope.colonne.list[x.name] = false;
            return x.name;
          });
          var dialog = ngDialog.openConfirm({
            template:
              'js/XG/widgets/hpoapp/analye_multicritere/views/dialog/hpo.removecolonne.html',
            className: 'ngdialog-theme-plain width800 nopadding miniclose',
            scope: scope,
          });
          dialog.then(function(data) {
            if (data) {
              var callback = function(isconfirm) {
                if (isconfirm) {
                  for (var key in data.list) {
                    if (
                      key &&
                      data.list.hasOwnProperty(key) &&
                      data.list[key]
                    ) {
                      var names = scope.gridHpo.columnDefs.map(function(x) {
                        return x.name;
                      });
                      var idx = names.indexOf(key);
                      if (~idx) {
                        scope.gridHpo.columnDefs.splice(idx, 1);
                        scope.gridHpo.data.map(function(x) {
                          if (x.hasOwnProperty(key)) delete x[key];
                        });
                        scope.data = scope.gridHpo.data;
                        scope.columnDefs = scope.gridHpo.columnDefs;
                      }
                    }
                  }
                  scope.data = scope.gridHpo.data;
                  scope.columnDefs = scope.gridHpo.columnDefs;
                  scope.gridApi.core.notifyDataChange(
                    uiGridConstants.dataChange.ALL
                  );
                  AlertHpoFactory.successDelete();
                  try {
                    scope.$apply();
                  } catch(err) {}
                }
              };
              var message =
                $filter('translate')(
                  'hpo.multicritere.parameters.removecolumn'
                ) +
                '. ' +
                $filter('translate')('hpo.common.sur');
              AlertHpoFactory.alertConfirmCallback(
                $filter('translate')('hpo.common.warning'),
                message,
                'warning',
                true,
                undefined,
                '#F50072',
                true,
                undefined,
                undefined,
                true,
                true,
                callback
              );
            }
          });
        };

        scope.emptySelection = function() {
          scope.gridApi.selection.clearSelectedRows();
        };

        scope.filterFunc = HpoCarteAppFactory.getAppFactory().filterFunc;

        scope.emptyTable = function() {
          var callback = function(isconfirm) {
            if (isconfirm) {
              scope.gridHpo.data = [];
              scope.gridHpo.columnDefs = [];
              scope.data = scope.gridHpo.data;
              scope.columnDefs = scope.gridHpo.columnDefs;
              scope.gridApi.core.notifyDataChange(
                uiGridConstants.dataChange.ALL
              );
              try {
                scope.$apply();
              } catch(err) {}
            }
          };
          var message =
            $filter('translate')('hpo.multicritere.parameters.emptytable') +
            '. ' +
            $filter('translate')('hpo.common.sur');
          AlertHpoFactory.alertConfirmCallback(
            $filter('translate')('hpo.common.warning'),
            message,
            'warning',
            true,
            undefined,
            '#F50072',
            true,
            undefined,
            undefined,
            true,
            true,
            callback
          );
        };

        scope.ftis = HpoCarteAppFactory.getAppFactory().getMulticritereFtis();

        scope.getUniqueValues = function(selection) {
          var analysis = {
            analysistool: 'distributionanalysis',
            tableselected: selection.fti,
            result: [],
            geoj: {},
            operands: [],
            attributestoselect: {},
            expression: '',
            interpreteattributes: 'and',
            interpreteconditions: 'and',
            selectedall: false,
            attributestouseindatatable: [],
            supplementAttributes: null,
            adminConfig: HpoCarteAppFactory.getInitProvider().getHpoConfig(),
          };
          if (selection.hasOwnProperty('attribute'))
            analysis.attributestoselect[selection.attribute.name] = true;
          else if (selection.hasOwnProperty('selected_attributes')) {
            Object.keys(selection.selected_attributes).map(function(x) {
              if (selection.selected_attributes[x]) {
                analysis.attributestoselect[x] = true;
              }
            });
          }
          gaDomUtils.showGlobalLoader();
          HpoAppServices.analyseData(analysis).then(
            function(res) {
              if (
                res.data &&
                res.data.status &&
                res.data.result &&
                res.data.result.length > 0
              ) {
                selection.results = res.data.result[0];
                if (res.data.result.length > 1)
                  selection.results2 = res.data.result[1];
                try {
                  if (
                    selection.results &&
                    selection.results.result &&
                    selection.results.result.length === 0
                  ) {
                    AlertHpoFactory.getSimpleSuccess(
                      $filter('translate')('hpo.common.success'),
                      $filter('translate')(
                        'hpo.data.prepare.analysissuccessbutnodata'
                      ),
                      true,
                      'info'
                    );
                  }
                } 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();
            }
          );
        };

        scope.changedFtiCoLumn = function() {
          Object.assign(scope.selection, {
            attribute: undefined,
            selected_values: {},
            results: undefined,
            authorisedAttributes: HpoCarteAppFactory.getAppFactory().getAuthorizedAttributes(
              scope.selection.fti
            ),
          });
        };

        scope.addColumnAttribute = function() {
          scope.selection = {
            fti: undefined,
            attribute: undefined,
            selected_values: {},
            results: undefined,
          };
          var dialog = ngDialog.openConfirm({
            template:
              'js/XG/widgets/hpoapp/analye_multicritere/views/dialog/hpo.addattributefromcomponent.html',
            className: 'ngdialog-theme-plain width1100 nopadding miniclose',
            scope: scope,
          });
          dialog.then(function(data) {
            if (data) {
              if (scope.gridHpo.data.length > 0) {
                var callback = function(isconfirm) {
                  if (isconfirm) {
                    checkOrAddColumnDef(
                      data.attribute.name,
                      data.attribute.alias
                    );
                    var i = 0;
                    var length = scope.gridHpo.data.length;
                    Object.keys(data.selected_values).map(function(x) {
                      if (
                        x &&
                        data.selected_values.hasOwnProperty(x) &&
                        data.selected_values[x]
                      ) {
                        if (i < length) {
                          scope.gridHpo.data[i][data.attribute.name] = x;
                          i++;
                        } else {
                          var obj = {};
                          obj[data.attribute.name] = x;
                          scope.gridHpo.data.push(obj);
                        }
                      }
                    });
                    scope.data = scope.gridHpo.data;
                    scope.columnDefs = scope.gridHpo.columnDefs;
                    scope.gridApi.core.notifyDataChange(
                      uiGridConstants.dataChange.ALL
                    );
                    try {
                      scope.$apply();
                    } catch(err) {}
                  }
                };
                var message =
                  $filter('translate')(
                    'hpo.multicritere.parameters.notemptytable'
                  ) +
                  '. ' +
                  $filter('translate')('hpo.multicritere.parameters.continue');
                AlertHpoFactory.alertConfirmCallback(
                  $filter('translate')('hpo.common.warning'),
                  message,
                  'warning',
                  true,
                  undefined,
                  '#F50072',
                  true,
                  undefined,
                  undefined,
                  true,
                  true,
                  callback
                );
              } else {
                checkOrAddColumnDef(data.attribute.name, data.attribute.alias);
                Object.keys(data.selected_values).map(function(x) {
                  if (
                    x &&
                    data.selected_values.hasOwnProperty(x) &&
                    data.selected_values[x]
                  ) {
                    var obj = {};
                    obj[data.attribute.name] = x;
                    scope.gridHpo.data.push(obj);
                  }
                });
                scope.data = scope.gridHpo.data;
                scope.columnDefs = scope.gridHpo.columnDefs;
                scope.gridApi.core.notifyDataChange(
                  uiGridConstants.dataChange.ALL
                );
                AlertHpoFactory.successUpdate();
              }
            }
          });
        };

        scope.changedFtiTable = function() {
          Object.assign(scope.selection, {
            selected_attributes: {},
            selected_values: {},
            selected_values2: {},
            results: undefined,
            results2: undefined,
            position: {},
            authorisedAttributes: HpoCarteAppFactory.getAppFactory().getAuthorizedAttributes(
              scope.selection.fti
            ),
          });
        };

        var addColumnOrHeader = function(
          attribute,
          selected_values,
          position,
          isEmptyTable
        ) {
          switch (position) {
            case 'column':
              scope.gridHpo.columnDefs.splice(0, 0, {
                name: attribute.name,
                displayName: attribute.alias,
                headerTooltip: true,
                cellTooltip: true,
                enableCellEdit: true,
                enableFiltering: scope.gridHpo.enableFiltering,
              });
              var i = 0;
              var length = scope.gridHpo.data.length;
              Object.keys(selected_values).map(function(x) {
                if (
                  x &&
                  selected_values.hasOwnProperty(x) &&
                  selected_values[x]
                ) {
                  if (isEmptyTable) {
                    var obj = {};
                    obj[attribute.name] = x;
                    scope.gridHpo.data.push(obj);
                  } else {
                    if (i < length) {
                      scope.gridHpo.data[i][attribute.name] = x;
                      i++;
                    } else {
                      var obj = {};
                      obj[attribute.name] = x;
                      scope.gridHpo.data.push(obj);
                    }
                  }
                }
              });
              break;
            case 'header':
              Object.keys(selected_values).map(function(x) {
                if (
                  x &&
                  selected_values.hasOwnProperty(x) &&
                  selected_values[x]
                ) {
                  checkOrAddColumnDef(x, x);
                  scope.gridHpo.data.map(function(y) {
                    if (!y.hasOwnProperty(x)) y[x] = undefined;
                  });
                }
              });
              break;
          }
          scope.data = scope.gridHpo.data;
          scope.columnDefs = scope.gridHpo.columnDefs;
        };

        scope.createTable = function() {
          scope.selection = {
            fti: undefined,
            selected_attributes: {},
            selected_values: {},
            selected_values2: {},
            results: undefined,
            results2: undefined,
            position: {},
          };
          var dialog = ngDialog.openConfirm({
            template:
              'js/XG/widgets/hpoapp/analye_multicritere/views/dialog/hpo.create_table_from_attributes.html',
            className: 'ngdialog-theme-plain width1100 nopadding miniclose',
            scope: scope,
          });
          dialog.then(function(data) {
            if (data) {
              if (scope.gridHpo.data.length > 0) {
                var callback = function(isconfirm) {
                  if (isconfirm) {
                    var name = data.results.name;
                    var position = data.position[name];
                    var name2 = data.results2.name;
                    var position2 = data.position[name2];
                    if (position === 'column') {
                      addColumnOrHeader(
                        data.results.attribute,
                        data.selected_values,
                        position,
                        false
                      );
                      addColumnOrHeader(
                        data.results2.attribute,
                        data.selected_values2,
                        position2,
                        false
                      );
                    } else {
                      addColumnOrHeader(
                        data.results2.attribute,
                        data.selected_values2,
                        position2,
                        false
                      );
                      addColumnOrHeader(
                        data.results.attribute,
                        data.selected_values,
                        position,
                        false
                      );
                    }
                    scope.data = scope.gridHpo.data;
                    scope.columnDefs = scope.gridHpo.columnDefs;
                    scope.gridApi.core.notifyDataChange(
                      uiGridConstants.dataChange.ALL
                    );
                    try {
                      scope.$apply();
                    } catch(err) {}
                  }
                };
                var message =
                  $filter('translate')(
                    'hpo.multicritere.parameters.notemptytable'
                  ) +
                  '. ' +
                  $filter('translate')('hpo.multicritere.parameters.continue');
                AlertHpoFactory.alertConfirmCallback(
                  $filter('translate')('hpo.common.warning'),
                  message,
                  'warning',
                  true,
                  undefined,
                  '#F50072',
                  true,
                  undefined,
                  undefined,
                  true,
                  true,
                  callback
                );
              } else {
                var name = data.results.name;
                var position = data.position[name];
                var name2 = data.results2.name;
                var position2 = data.position[name2];
                if (position === 'column') {
                  addColumnOrHeader(
                    data.results.attribute,
                    data.selected_values,
                    position,
                    true
                  );
                  addColumnOrHeader(
                    data.results2.attribute,
                    data.selected_values2,
                    position2,
                    true
                  );
                } else {
                  addColumnOrHeader(
                    data.results2.attribute,
                    data.selected_values2,
                    position2,
                    true
                  );
                  addColumnOrHeader(
                    data.results.attribute,
                    data.selected_values,
                    position,
                    true
                  );
                }
                scope.data = scope.gridHpo.data;
                scope.columnDefs = scope.gridHpo.columnDefs;
                scope.gridApi.core.notifyDataChange(
                  uiGridConstants.dataChange.ALL
                );
                AlertHpoFactory.successUpdate();
              }
            }
          });
        };

        scope.selectAllTable = function(result, selected_values) {
          result.map(function(x) {
            selected_values[x.value] = true;
          });
        };

        scope.deselectAllTable = function(result, selected_values) {
          result.map(function(x) {
            selected_values[x.value] = false;
          });
        };

        scope.$watch('data', function(newval) {
          if (newval) {
            scope.gridHpo.data = scope.data;
            scope.gridHpo.columnDefs = scope.columnDefs;
          }
        });
      },
    };
  };

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