'use strict';
define(function() {
  var personneInfosPicker = function(
    ngDialog,
    AncAppFactory,
    BacAppFactory,
    gaDomUtils,
    $rootScope
  ) {
    return {
      templateUrl:
        'js/XG/widgets/ancapp/main/views/directives/personne_infos_picker.html',
      scope: {
        res: '=', //result
        dossier: '=',
        buttonStyle: '=?', //use a special button
        type: '=?',
        saveReport: '&', //type of person
      },

      restrict: 'EA',
      link: function(scope, element, attr) {
        var CurrentAppFactory = !AncAppFactory.appCfg.main
          ? BacAppFactory
          : AncAppFactory;

        if (
          angular.isDefined(
            CurrentAppFactory.appCfg.main.properties.setDateDebutPropObligatoire
          ) &&
          CurrentAppFactory.appCfg.main.properties.setDateDebutPropObligatoire
        ) {
          scope.dateDebutProp = true;
          scope.infoProp = { properties: {} };
        } else {
          scope.dateDebutProp = false;
        }

        scope.select = {};
        scope.personnes = [];
        scope.nomPersonnes = 0;
        var checkUnique = function(pers, per) {
          var res = true;
          pers.forEach(function(p) {
            if (p.id == per.id) {
              res = false;
            }
          });
          return res;
        };

        var initpersonne = function() {
          if (scope.dossier && scope.dossier.properties) {
            var nomPersonnes =  (scope.dossier.properties.proprietaires?scope.dossier.properties.proprietaires.length:0) +  
                                (scope.dossier.properties.locataires?scope.dossier.properties.locataires.length:0);

            //Ajouter toue les personnes du dossier dans le tableau
            if (nomPersonnes != 0) {
              scope.personnes = [];
              var locataire =
                angular.copy(scope.dossier.properties.locataires[0]) || {};
              //var demandeur = angular.copy(scope.dossier.properties.demandeurs[0]) || {};
              var proIds = [];
              // proprietaires
              for (
                var i = 0;
                i < scope.dossier.properties.proprietaires.length;
                i++
              ) {
                var proprietaire = angular.copy(
                  scope.dossier.properties.proprietaires[i]
                );
                proIds.push(proprietaire.id);
                if (
                  checkUnique(scope.personnes, proprietaire) &&
                  scope.type != 'proprietaires'
                ) {
                  scope.personnes.push(proprietaire);
                }
              }
              // locataire
              if (scope.dossier.properties.locataires[0]) {
                if (
                  checkUnique(scope.personnes, locataire) &&
                  scope.type != 'locataires'
                ) {
                  var contain = false;
                  if (scope.type == 'proprietaires') {
                    proIds.forEach(function (id) {
                      if (id == locataire.id) contain = true;
                    });
                  }
                  if (contain == false) {
                    scope.personnes.push(locataire);
                  }
                }
                if (scope.type == 'locataires') {
                  for (var i = 0; i < scope.personnes.length; i++) {
                    if (scope.personnes[i].id == locataire.id) {
                      scope.personnes.splice(i, 1);
                    }
                  }
                }
              }
              // enlever les memes objets dans le tableau
              var unique = {};
              scope.personnes.forEach(function (personne) {
                unique[JSON.stringify(personne)] = personne;
              });
              scope.personnes = Object.keys(unique).map(function (u) {
                return JSON.parse(u);
              });
            }
          }
        };
        initpersonne();

        var personne_infos_picker_dialog;
        scope.openDialogUsersDuDossier = () => {
          if (scope.dossier.properties.proprietaires.length === 1) {
            scope.select.personne = scope.dossier.properties.proprietaires[0];
            scope.choisirPersonneDuDossier();
          } else {
            scope.select = { personne: {} };
            personne_infos_picker_dialog = ngDialog.open({
              template:
                'js/XG/widgets/ancapp/main/views/directives/personne_infos_picker_dialog.html',
              className: 'ngdialog-theme-plain width800 nopadding miniclose',
              closeByDocument: false,
              scope: scope,
            });
          }
        };

        /**
         * refresh la liste de personnes
         */
        var refreshDossierPersonne = $rootScope.$on(
          'refreshDossierPersonne',
          () => {
            initpersonne();
          }
        );

        var setHideEqual = $rootScope.$on('setHideEqual', (event, params) => {
          scope.hideEqual = params.flag;
        });

        scope.$on('addPropAsLoc', (event, data) => {
          if (!event.defaultPrevented) {
            event.defaultPrevented = true;

            if (data) {
              scope.dossier.properties.locataires = angular.isDefined(
                scope.dossier.properties.locataires
              )
                ? scope.dossier.properties.locataires
                : [];
              scope.dossier.properties.locataires.push(data);
              initpersonne();
            }
          }
        });
        /**
         * choisir une personne du dossier
         */
        scope.choisirPersonneDuDossier = function() {
          gaDomUtils.showGlobalLoader();
          CurrentAppFactory.getpersonne(scope.select.personne.id).then(
            res => {
              CurrentAppFactory.addpersonnetodossier(scope.type,scope.dossier.id,scope.select.personne.id,scope.select.personne.debut ? scope.select.personne.debut : null, null, null,scope.select.personne.fin ? scope.select.personne.fin : null).then((res)=>{
                if (personne_infos_picker_dialog) {
                  personne_infos_picker_dialog.close();                
                }
                
                scope.saveReport();
                gaDomUtils.hideGlobalLoader();
              },(()=>{
                if (personne_infos_picker_dialog) {
                  personne_infos_picker_dialog.close();
                }
                scope.saveReport();
                gaDomUtils.hideGlobalLoader();
              }))
            },
            () => {
              if (personne_infos_picker_dialog) {
                personne_infos_picker_dialog.close();
              }
              gaDomUtils.hideGlobalLoader();
            }
          );
        };

        // cleanup
        scope.$on('$destroy', function() {
          refreshDossierPersonne();
        });
      },
    };
  };

  personneInfosPicker.$inject = [
    'ngDialog',
    'AncAppFactory',
    'BacAppFactory',
    'gaDomUtils',
    '$rootScope',
  ];
  return personneInfosPicker;
});
