'use strict';
define(function() {
  var saveAndGetTemplateHpo = 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/save_and_get_template_hpo.html',
      restrict: 'EA',
      scope: {
        configName: '=',
        data: '=',
        saveTemplateHtml: '=?',
        getTemplateHtml: '=?',
        verifyLoadedData: '=?',
        runReturn: '=?',
        res: '=?',
        excludeProperties: '=?',
        icons: '=?',
        specialPreTreatement: '=?',
        disableButtons: '=?',
      },
      link: function(scope, elt, attrs, ctrl) {
        scope.writequeryname = true;
        scope.changeWrtieMode = function() {
          scope.writequeryname = !scope.writequeryname;
        };

        if (angular.isUndefined(scope.saveTemplateHtml))
          scope.saveTemplateHtml =
            'js/XG/widgets/hpoapp/main/views/templates/data/hpo.data.prepare.templates.html';
        if (angular.isUndefined(scope.getTemplateHtml))
          scope.getTemplateHtml =
            'js/XG/widgets/hpoapp/main/views/templates/data/hpo.data.prepare.gettemplates.html';

        var ngDialogPromise;
        scope.saveTemplate = function() {
          ParametersFactory.getbytype(scope.configName).then(
            function(res) {
              if (res.data.length > 0) {
                scope.datas = res.data;
                scope.saved = {
                  realNames: scope.datas,
                  queries: scope.datas
                    .map(function(x) {
                      return x.name;
                    })
                    .filter(function(x) {
                      if (x) return x;
                    }),
                };
              }
            },
            function(data) {
              console.log(scope.config);
            }
          );
          var data = angular.copy(scope.data);
          if (scope.excludeProperties)
            data = Object.assign(data, scope.excludeProperties);
          if (scope.specialPreTreatement)
            data = scope.specialPreTreatement(data);

          scope.saveData = {
            user: $rootScope.xgos.user.login,
            savedata: data,
          };
          scope.queryname = undefined;
          ngDialogPromise = ngDialog.openConfirm({
            template: scope.saveTemplateHtml,
            scope: scope,
            className: 'ngdialog-theme-plain width600 nopadding miniclose',
          });
          ngDialogPromise.then(
            function(data) {
              ParametersFactory.getbytype(scope.configName).then(function(res) {
                var nameSaved = res.data.map(function(x) {
                  return x.name;
                });
                if (nameSaved.indexOf(data) !== -1) {
                  var idx = res.data
                    .map(function(x) {
                      return x.name;
                    })
                    .indexOf(data);
                  var id = res.data[idx].id;
                  ParametersFactory.remove(id).then(
                    function() {
                      ParametersFactory.add(
                        scope.saveData,
                        scope.configName,
                        data
                      ).then(
                        function() {
                          require('toastr').success(
                            $filter('translate')('elastic.search.save_ok')
                          );
                        },
                        function() {
                          require('toastr').error(
                            $filter('translate')('elastic.search.save_nok')
                          );
                        }
                      );
                    },
                    function() {
                      require('toastr').error(
                        $filter('translate')('elastic.search.save_nok')
                      );
                    }
                  );
                } else {
                  ParametersFactory.add(
                    scope.saveData,
                    scope.configName,
                    data
                  ).then(
                    function() {
                      require('toastr').success(
                        $filter('translate')('elastic.search.save_ok')
                      );
                    },
                    function() {
                      require('toastr').error(
                        $filter('translate')('elastic.search.save_nok')
                      );
                    }
                  );
                }
              });
            },
            function(data) {
              require('toastr').info(
                $filter('translate')('elastic.search.annuler')
              );
            }
          );
        };

        scope.removeSavedAdvanced = function(idx, array) {
          var callback = function(confirmed) {
            if (confirmed) {
              $timeout(function() {
                ParametersFactory.deletebytypeandname(
                  scope.saved.realNames[idx].name,
                  scope.saved.realNames[idx].type
                ).then(
                  function(res) {
                    if (res.data == 'true') {
                      scope.saved.realNames.splice(idx, 1);
                      scope.saved.queries.splice(idx, 1);
                      AlertHpoFactory.successDelete();
                    } else {
                      AlertHpoFactory.failDelete();
                    }
                  },
                  function(res) {
                    AlertHpoFactory.getSimpleFail(
                      $filter('translate')('hpo.data.exchange.fail'),
                      $filter('translate')('hpo.data.exchange.updatesfail'),
                      true
                    );
                  }
                );
              }, 600);
            }
          };
          AlertHpoFactory.alertConfirmCallback(
            $filter('translate')('hpo.common.warning'),
            $filter('translate')('hpo.data.exchange.templateremove'),
            'warning',
            true,
            undefined,
            '#F50072',
            true,
            undefined,
            undefined,
            true,
            true,
            callback
          );
        };

        scope.getTemplate = function() {
          ParametersFactory.getbytype(scope.configName).then(
            function(res) {
              if (res.data.length > 0) {
                scope.datas = res.data;
                scope.saved = {
                  realNames: scope.datas,
                  queries: scope.datas
                    .map(function(x) {
                      return x.name;
                    })
                    .filter(function(x) {
                      if (x) return x;
                    }),
                };
                scope.currentuser = $rootScope.xgos.user.login;
                ngDialogPromise = ngDialog.openConfirm({
                  template: scope.getTemplateHtml,
                  scope: scope,
                  className:
                    'ngdialog-theme-plain width600 nopadding miniclose',
                });
                ngDialogPromise.then(
                  function(data) {
                    if (data && data.query) {
                      var filename = data.query;
                      var filenames = scope.datas.map(function(x) {
                        return x.name;
                      });
                      var index = filenames.indexOf(filename);
                      var dataHPO = scope.datas[index].data;

                      if (angular.isDefined(scope.verifyLoadedData))
                        scope.verifyLoadedData(dataHPO);
                      scope.res = dataHPO;
                      if (angular.isDefined(scope.runReturn))
                        scope.runReturn(dataHPO);
                    }
                  },
                  function(data) {
                    require('toastr').info(
                      $filter('translate')('elastic.search.annuler')
                    );
                  }
                );
              } else {
                require('toastr').info(
                  $filter('translate')('elastic.search.no_save')
                );
              }
            },
            function() {
              require('toastr').error(
                $filter('translate')('elastic.search.save_nok')
              );
            }
          );
        };
      },
    };
  };

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