/**
 *
 */
'use strict';
define(function() {
  /**
   * DataStore Ctrl
   * @param $scope
   * @param DataStoreFactory
   * @constructor
   */
  var DataStoreCtrl = function(
    $scope,
    $filter,
    DataStoreFactory,
    gaDomUtils,
    $rootScope,
    PortalsFactory,
    ngDialog
    ) {
    /**
     * Create or update the datastore
     */
    $scope.editDataStore = function(form) {
      gaDomUtils.showGlobalLoader();
      console.log($scope.edit_resource);
      if ($scope.isNewResource) {
        // dont close the dialog so the user can test the connexion
        DataStoreFactory.add($scope.edit_resource)
          .then(function(res) {
            $scope.isNewResource = false;
            $scope.edit_resource.uid = res.data.uid;
            require('toastr').success('ok');
            form.$setPristine();
          })
          .finally(gaDomUtils.hideGlobalLoaderAfterTimeout);
      } else {
        DataStoreFactory.update(
          $scope.edit_resource,
          $scope.oldcopy &&
            $scope.oldcopy.name &&
            $scope.oldcopy.name !== $scope.edit_resource.name
            ? $scope.oldcopy.name
            : ''
          ).then(function() {
            require('toastr').success('ok');
            form.$setPristine();
          })
          .finally(gaDomUtils.hideGlobalLoaderAfterTimeout);
      }
    };

    /**
    
     * DataStore removal
     */
    $scope.removeDataStore = () => {
      DataStoreFactory.remove(
        $scope.edit_resource.name,
        $scope.edit_resource.uid
      );
    };

    /**
     * cette fonction applique le script d'anonymisation de la BD
     */
    $scope.anonymizeDb = () => {
      swal({
        title: $filter('translate')('datastores.anonymizeDb'),
        text: $filter('translate')('datastores.anonymizeDbConfirm'),
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d9534f',
        confirmButtonText: $filter('translate')('common.yes'),
        cancelButtonText: $filter('translate')('common.no'),
        closeOnConfirm: true,
        closeOnCancel: true,
      },
      (confirmed) => {
        if(confirmed){
          DataStoreFactory.anonymizeDb($scope.edit_resource.name).then(()=>{
            require('toastr').success(
              $filter('translate')('datastores.anonymizeDbOk')
            );
          },()=>{
            require('toastr').error(
              $filter('translate')('datastores.anonymizeDbNok')
            );
          });
        }
      });
    }

    /**
     * Datastores loading
     */
    $scope.currentResources = DataStoreFactory.resources.datastores;

    if (DataStoreFactory.resources.datastores.length == 0) {
      DataStoreFactory.get().then(function() {
        $scope.currentResources = DataStoreFactory.resources.datastores;
      });
    }

    /**
     * Connexion to the datastore test
     */
    $scope.connectionTest = function() {
      $scope.connectionTestIsProcessing = true;
      DataStoreFactory.connect_test($scope.edit_resource.name).then(
        function(connected) {
          if (connected) {
            require('toastr').success(
              $filter('translate')('datastores.connexion.connexion_ok')
            );
          } else {
            require('toastr').error(
              $filter('translate')('datastores.connexion.connexion_nok')
            );
          }
          $scope.connectionTestIsProcessing = false;
        },
        function() {
          require('toastr').error(
            $filter('translate')('datastores.connexion.connexion_nok')
          );
          $scope.connectionTestIsProcessing = false;
        }
      );
    };

    let createOrRepairDBDialog;
    /**
     * ouvrir un dialog pour saisir le nom/ mdp et bdd de maintenance de l'admin
     */
    $scope.openDialogCreateOrRepairDb = () => {
      $scope.createOrRepairDBParam = {};
      $scope.createOrRepairDBParam.dbAdmin = 'postgres';
      $scope.createOrRepairDBParam.password = '';
      $scope.createOrRepairDBParam.maintenanceDB = 'postgres';
      $scope.createOrRepairDBParam.nameDB = $scope.edit_resource.name; 
      createOrRepairDBDialog = ngDialog.open({
        template:
          'js/XG/containers/views/createOrRepairDB.html',
        className: 'ngdialog-theme-plain',
        closeByDocument: false,
        scope: $scope,
      });
    }

    /**
     * Lancer la fonction create ou réparer la bdd et gérer les msg de retour
     */
    $scope.createOrRepairDB = () => {
      DataStoreFactory.createOrRepairDB($scope.createOrRepairDBParam).then( () => {
        require('toastr').success(
          $filter('translate')('datastores.createOrRepairDB.succes')
        );
        $scope.CloseCreateOrRepairDb();
      }, (err) => {
        let msg;

        switch (true) {
          case err.data.startsWith('connectionAdmin'):
            msg = 'connectionAdmin';
            break;
          case err.data.startsWith('createUser'):
            msg = 'createUser';
            break;
          case err.data.startsWith('checkDbExistence'):
            msg = 'checkDbExistence';
            break;
          case err.data.startsWith('createDb'):
            msg = 'createDb';
            break;
          case err.data.startsWith('grantAllPrivileges'):
            msg = 'grantAllPrivileges';
            break;
          case err.data.startsWith('connectionBd'):
            msg = 'connectionBd';
            break;
          case err.data.startsWith('createSchema'):
            msg = 'createSchema';
            break;
          case err.data.startsWith('createExtension'):
            msg = 'createExtension';
            break;
          case err.data.startsWith('stForce2d'):
            msg = 'stForce2d';
            break;
          default:
            msg = 'error';
        }

        require('toastr').error(
          $filter('translate')('datastores.createOrRepairDB.errorMessages.' + msg)
        );

        if (!err.data.startsWith('connectionAdmin')) {
          $scope.CloseCreateOrRepairDb();
        }

      });
    }

    /**
     * fermer le dialog s'il est tjrs ouvert
     */
    $scope.CloseCreateOrRepairDb = () => {
      if(createOrRepairDBDialog){
        createOrRepairDBDialog.close();
      }
    }

    /**
         EditList Directive configuration
         */
    $scope.editListCfg = {
      dataModule: 'model',
      resource_type: 'datastores',
      cols: ['name', 'type', 'host', 'database'],
      colsFunction: {
        type: 'dataStoreTypeLogo',
      },
      removeFunction: $scope.removeDataStore,
      deleteConfirmText:  $filter('translate')('datastores.delete_all_components_confirm'),
      extraGlobalActions: [],
    };

    let anonymizeDb = {
      icon: "<i class='fa fa-user-secret'></i>",
      label: 'datastores.anonymizeDb',
      fn: $scope.anonymizeDb,
      disablefn: () => {
        return !($scope.edit_resource && $scope.edit_resource.name);
      },
    }

    // je sépare les conditions pour ne pas envoyer une requete si c'est root
    if($rootScope.xgos.isroot){
      PortalsFactory.getCommonInfo().then((res)=>{
        if(res.data.BASE_ANONYMISATION){
          $scope.editListCfg.extraGlobalActions.push(anonymizeDb);
        }
      });
    }

    if (DataStoreFactory.specialHpoAppUid.uid)
      Object.assign($scope.editListCfg, {
        deleteResourceButton: false,
        addResourceButton: false,
      });

    /*
     * DataStore Types
     */
    $scope.dataStoresTypes = [
      {
        label: 'ArcGIS',
        value: 'ArcGis',
      },
      {
        label: 'PostGIS',
        value: 'postgis',
      },
      {
        label: 'PostgreSQL (Experimental)',
        value: 'safepostgis',
      },
      {
        label: 'MySQL',
        value: 'mysql',
      },
      {
        label: 'Oracle',
        value: 'oracle',
      },
      {
        label: 'SQL Server',
        value: 'sqlserver',
      },
    ];

    $scope.validForm = {};
    $scope.validateName = function() {
      var actualName = $scope.edit_resource.name;
      $scope.$watch(
        'edit_resource.name',
        function(name) {
          $scope.nameExists =
            $scope.currentResources
              .map(function(r) {
                return r.name;
              })
              .indexOf(name) != -1;
          if (!$scope.isNewResource && $scope.edit_resource.name == actualName)
            $scope.nameExists = false;
          $scope.validForm.name = !$scope.nameExists;
        },
        1
      );
    };
  };

  DataStoreCtrl.$inject = [
    '$scope',
    '$filter',
    'DataStoreFactory',
    'gaDomUtils',
    '$rootScope',
    'PortalsFactory',
    'ngDialog'
  ];
  return DataStoreCtrl;
});
