'use strict';
define(function() {
  var varianteCtrl = function(
    $scope,
    ParametersFactory,
    $location,
    ngDialog,
    FeatureAttachmentFactory,
    $filter,
    gaDomUtils,
    SirocoFactory,
    $timeout
  ) {
    $scope.currentVariante = false;
    $scope.criticiteTypes = [
      { label: 'Normale' },
      { label: 'Simplifiée' },
      { label: 'Casse' },
    ];
    var sirocoCfg = JSON.parse(sessionStorage.getItem('sirocoCfg'));

    // get parametrages
    var getParametrages = function() {
      $scope.parametrages = [];
      ParametersFactory.getbytype('siroco_corpshypo').then(function(res) {
        if (res.data.length > 0) {
          res.data.forEach(function(cfg) {
            if (cfg.data.app == sirocoCfg.appuid) {
              $scope.parametrages.push(cfg);
            }
          });
        }
      });
    };

    // get ponderations
    var getPonderations = function() {
      $scope.ponderations = [];
      ParametersFactory.getbytype('siroco_ponderation').then(function(res) {
        if (res.data.length > 0) {
          res.data.forEach(function(cfg) {
            if (cfg.data.app == sirocoCfg.appuid) {
              $scope.ponderations.push(cfg);
            }
          });
        }
      });
    };

    var getFichiersCasse = function() {
      $scope.fichiersCasse = [];
      FeatureAttachmentFactory.list('siroco', 'casse').then(function(res) {
        $scope.fichiersCasse = res.data;
      });
    };

    var getFichierCriticite = function() {
      $scope.fichierCriticite = false;
      FeatureAttachmentFactory.list('siroco', 'criticite').then(function(res) {
        if (res.data.length > 0) {
          $scope.fichierCriticite = res.data[0];
        }
      });
    };

    /**
     * load the list of cfg
     */
    $scope.refresh = function() {
      $scope.currentVariante = false;
      $scope.cfgList = [];
      ParametersFactory.getbytype('siroco_variante').then(function(res) {
        if (res.data.length > 0) {
          res.data.forEach(function(cfg) {
            if (cfg.data.app == sirocoCfg.appuid) {
              $scope.cfgList.push(cfg);
            }
          });
        }
        getParametrages();
        getPonderations();
        getFichierCriticite();
        getFichiersCasse();
      });
    };
    $scope.refresh();

    /**
     * Génerer une variante
     */
    $scope.genererVariante = function() {
      gaDomUtils.showGlobalLoader();
      gaDomUtils.setGlobalLoaderScale(0, 100);

      SirocoFactory.generationvariante(
        sirocoCfg.appname,
        'Generer',
        $scope.currentVariante.name
      ).then(
        function(res) {
          if (res.data.ok) {
            SirocoFactory.checkGeneration(
              res.data.strValeur,
              $scope.currentVariante.name,
              'GenerationVariante',
              'CheckGeneration'
            ).then(function(res) {
              var response = res.data.strValeur;
              if (response.indexOf(';;;;') != -1) {
                response = response.split(';;;;');
                response[1] = response[1].replace(/\n/g, '<br/>');
                // error
                if (response[0] == 'erreur') {
                  require('toastr').error(
                    response[1],
                    'Erreur lors de la génération de la variante',
                    {
                      closeButton: true,
                      timeOut: '0',
                      extendedTimeOut: '0',
                      positionClass: 'toast-bottom-full-width',
                    }
                  );
                  gaDomUtils.hideGlobalLoader();
                  return;
                  // ok
                } else if (response[0] == 'ok') {
                  // warning
                } else {
                  require('toastr').warning(
                    response[1],
                    'Informations relatives à la génération de la variante',
                    {
                      closeButton: true,
                      timeOut: '0',
                      extendedTimeOut: '0',
                      positionClass: 'toast-bottom-full-width',
                    }
                  );
                }
              }
              gaDomUtils.setGlobalLoaderScaleValue(100);
              $timeout(function() {
                require('toastr').success('Génération terminée.');
                $scope.currentVariante.data.Generee = 'oui';
                $scope.saveVariante();
                gaDomUtils.hideGlobalLoader();
              }, 1000);
            });
          } else {
            require('toastr').error(
              res.data.errorMessage,
              'Erreur lors de la génération de la variante',
              {
                closeButton: true,
                timeOut: '0',
                extendedTimeOut: '0',
                positionClass: 'toast-bottom-full-width',
              }
            );
            gaDomUtils.hideGlobalLoader();
          }
          // error
        },
        function() {
          console.log('ERROR');
          gaDomUtils.hideGlobalLoader();
        }
      );
    };

    /**
     * Calcul de l'importance
     */
    $scope.calculerImportance = function() {
      gaDomUtils.showGlobalLoader();
      gaDomUtils.setGlobalLoaderScale(0, 100);

      SirocoFactory.calculimportancecanas(
        'calculer',
        $scope.currentVariante.name,
        sirocoCfg.appname
      ).then(
        function(res) {
          if (res.data.ok) {
            SirocoFactory.checkGeneration(
              res.data.strValeur,
              $scope.currentVariante.name,
              'CalculImportanceCanas',
              'CheckTreatment'
            ).then(function() {
              gaDomUtils.setGlobalLoaderScaleValue(100);
              $timeout(function() {
                require('toastr').success('Calcul importance terminé.');
                gaDomUtils.hideGlobalLoader();
              }, 1000);
            });
          } else {
            require('toastr').error(
              res.data.errorMessage,
              "Erreur dans lors du calcul de l'importance",
              {
                closeButton: true,
                timeOut: '0',
                extendedTimeOut: '0',
                positionClass: 'toast-bottom-full-width',
              }
            );
            gaDomUtils.hideGlobalLoader();
          }
          // error
        },
        function(res) {
          require('toastr').error('Erreur Serveur');
          gaDomUtils.hideGlobalLoader();
        }
      );
    };

    /**
     * newVarianteModal
     */
    $scope.newVarianteModal = function() {
      $scope.newVarianteData = {};
      ngDialog.open({
        template:
          'js/XG/widgets/sirocoapp/init/views/modals/modal.newvariante.html',
        className: 'ngdialog-theme-plain nopadding miniclose',
        closeByDocument: false,
        scope: $scope,
      });
    };
    /**
     * newVariante
     */
    $scope.newVariante = function() {
      var saveData = {
        app: sirocoCfg.appuid,
        /* Nom : $scope.newVarianteData.name,*/
        Generee: 'non',
      };

      ParametersFactory.add(
        saveData,
        'siroco_variante',
        $scope.newVarianteData.name
      ).then(function(res) {
        $scope.cfgList.push(res.data);
      });
    };

    /**
     * save Variante
     */
    $scope.saveVariante = function() {
      ParametersFactory.update(
        $scope.currentVariante,
        $scope.currentVariante.id
      ).then(function(res) {
        require('toastr').success($filter('translate')('common.saved'));
        $scope.allowGenerate = true;
      });
    };

    // force the user to save variante if its modified before he can access generateVariante and calculImportance
    $scope.allowGenerate = false;
    $scope.allowSave = false;
    $scope.$watch(
      'currentVariante',
      function(variante, old) {
        $scope.allowSave = false;
        var data = $scope.currentVariante.data;
        if (data && data.CorpsHypothese && data.Ponderation) {
          if (
            data.Type == 'Simplifiée' ||
            (data.Type == 'Normale' && data.FichierCriticite) ||
            (data.Type == 'Casse' && data.FichierCasse)
          ) {
            $scope.allowSave = true;
          }
        }

        // change in current variante
        if (variante.id == old.id) {
          $scope.allowGenerate = false;
          // new variante was loaded
        } else {
          $scope.allowGenerate = $scope.allowSave;
        }
      },
      1
    );

    /**
     * delete Variante
     */
    $scope.deleteVariante = function() {
      var ans = confirm(
        'Êtes-vous certain de vouloir supprimer cette variante ?'
      );
      if (ans) {
        ParametersFactory.remove($scope.currentVariante.id).then(function() {
          $scope.refresh();
        });
      }
    };

    /**
     * go to Casses page
     */
    $scope.goToCasses = function() {
      $location.path('/siroco/casses');
    };
  };

  varianteCtrl.$inject = [
    '$scope',
    'ParametersFactory',
    '$location',
    'ngDialog',
    'FeatureAttachmentFactory',
    '$filter',
    'gaDomUtils',
    'SirocoFactory',
    '$timeout',
  ];
  return varianteCtrl;
});
