'use strict';
define(
  function() {
  var ancPeriodesTarification = function(
    AncAppFactory,
    BacAppFactory,
    ngDialog
  ) {
    return {
      templateUrl:
        'js/XG/widgets/ancapp/main/views/directives/anc_periodes_tarification.html',
      restrict: 'EA',
      scope: {
        apptype: '=?',
        periodesCfg: '=',
      },
      link: function(scope, elt, attrs, ctrl) {
        var CurrentAppFactory =
          scope.apptype == 'bac' ? BacAppFactory : AncAppFactory;

        /*----------------------------------------------
         * PERIODES DE TARIFICATION
         *---------------------------------------------*/

        if (scope.apptype == 'bac') {
          scope.choixDateReferenceFacturation = [
            {
              value: 'date_saisie_controle',
              label: "Date de saisie de l'instruction",
            },
            {
              value: 'date_passage',
              label: "Date de l'instruction",
            },
            {
              value: 'date_avis',
              label: "Date de l'avis",
            },
          ];
        } else {
          scope.choixDateReferenceFacturation = [
            {
              value: 'date_saisie_controle',
              label: 'Date de saisie du controle',
            },
            {
              value: 'date_passage',
              label: 'Date du contrôle',
            },
            {
              value: 'date_avis',
              label: "Date de l'avis",
            },
          ];
        }

        for (var i in scope.periodesCfg.tarification) {
          scope.periodesCfg.tarification[i].tva = parseFloat(
            scope.periodesCfg.tarification[i].tva
          );
        }
        scope.editAncObj = {
          data: angular.copy(CurrentAppFactory.appCfg.main),
          options: { mode: 'tree' },
        };
        // Choose Database instead of Elastic
        scope.chooseDatabase = function() {
          // Passage de sa valeur à database
          CurrentAppFactory.appCfg.main.properties.billingQuery = 'database'
          CurrentAppFactory.updateAppCfg().then(() => {
            // this method only exist in AncAppFactory but work for both anc and bac
            AncAppFactory.createJsonbFieldInTableControle(CurrentAppFactory.appCfg.main.datastore, scope.apptype);
          }); 
        }

        var periodeDialog;
        scope.editedPeriode = null;
        scope.ouvrirPeriodeDialog = function() {
          scope.nouvellePeriode = {};
          periodeDialog = ngDialog.open({
            template:
              'js/XG/widgets/ancapp/main/views/modals/modal.periode.html',
            className: 'ngdialog-theme-plain width800 miniclose nopadding',
            closeByDocument: false,
            scope: scope,
          });
        };

        /**
         * Sauvegarde/update d'une période de tarification
         */
        scope.savePeriode = function() {
          // save
          if (scope.editedPeriode == null) {
            // add a unique key
            scope.nouvellePeriode.key = Date.now();
            scope.periodesCfg.periodes.push(scope.nouvellePeriode);
            // update
          } else {
            scope.periodesCfg.periodes[scope.editedPeriode] =
              scope.nouvellePeriode;
          }
          periodeDialog.close();
        };
        /**
         * verification du Nom de la Periode de facturation si il est déja utilisé 
         */
        scope.validPeriodeName = true;
        scope.verificationNomPeriodeUsed = () => {
          scope.$watch(
            'nouvellePeriode',
            function (nvlPeriode) {
              scope.validPeriodeName = true;
              if (
                Array.isArray(scope.periodesCfg.periodes) &&
                scope.periodesCfg.periodes.filter(
                  (periode) => periode.nom === nvlPeriode.nom
                ).length
              ) {
                scope.validPeriodeName = false;
              }
            },
            1
          );
        };

        /**
         * canDeletePeriode
         * retourne si possible de supprimer une période ou pas
         */
        scope.canDeletePeriode = function(key) {
          return CurrentAppFactory.appCfg.main.periodesCfg.tarification.filter(
            function(x) {
              return x.periode == key;
            }
          ).length;
        };

        scope.modifierPeriode = function(index) {
          scope.editedPeriode = index;
          scope.nouvellePeriode = scope.periodesCfg.periodes[index];

          periodeDialog = ngDialog.open({
            template:
              'js/XG/widgets/ancapp/main/views/modals/modal.periode.html',
            className: 'ngdialog-theme-plain width800 miniclose nopadding',
            closeByDocument: false,
            scope: scope,
            preCloseCallback: function() {
              scope.editedPeriode = null;
            },
          });
        };

        scope.supprimerPeriode = function(index) {
          var ans = confirm(
            'Êtes-vous certain de vouloir supprimer cette période ?'
          );
          if (ans) {
            scope.periodesCfg.periodes.splice(index, 1);
          }
        };
      },
    };
  };

  ancPeriodesTarification.$inject = [
    'AncAppFactory',
    'BacAppFactory',
    'ngDialog',
  ];
  return ancPeriodesTarification;
});
