'use strict';
define(function() {
  var ancBacDemandeurPicker = function(
    BacAppFactory,
    AncAppFactory,
    gaDomUtils,
    ngDialog,
    FeatureTypeFactory,
    EditFactory,
    $rootScope,
    gaJsUtils,
    $timeout
  ) {
    return {
      templateUrl:
        'js/XG/widgets/ancapp/main/views/anc_bac/anc_bac_demandeur_picker.html',
      restrict: 'EA',
      scope: {
        apptype: '=?',
        cdata: '=?', // controle data
        type: '=?', // lowercase du label de la valeur au sein de la restriction type du demandeur
        updatedb: '=?', // boolean utiliser pour déclencher ou non l'update de l'id demandeur en base, si undefined, trigger l'event
        changeDestination: '=?', // Sauvegarde le json à la clé précisée
      },
      link: function(scope, elt, attrs, ctrl) {
        var CurrentAppFactory =
          scope.apptype == 'bac' ? BacAppFactory : AncAppFactory;
        scope.entreprisesCfg = CurrentAppFactory.appCfg.main.entreprisesCfg;

        scope.labelToShow = 'Demandeur';

        scope.display = {};
        if (angular.isDefined(scope.type)) {
          scope.display[scope.type] = 'reduced';
          scope.labelToShow =
            scope.type.charAt(0).toUpperCase() + scope.type.slice(1);
        } else {
          scope.display.demandeur = 'reduced';
        }

        scope.expand = 0;
        scope.toggleDisplay = function() {
          scope.expand = scope.expand == 0 ? 1 : 0;

          if (
            angular.isDefined(scope.type) &&
            angular.isUndefined(scope.changeDestination)
          )
            scope.$emit(
              'toggleDisplayDemandeur',
              scope.display[scope.type],
              scope.type
            );
          else if (
            angular.isDefined(scope.type) &&
            angular.isDefined(scope.changeDestination)
          )
            scope.$emit(
              'toggleDisplayDemandeur',
              scope.display[scope.changeDestination],
              scope.changeDestination
            );
          else
            $rootScope.$emit('toggleDisplayDemandeur', scope.display.demandeur);
        };

        /*
                 LISTE ENTREPRISE 
                 */
        scope.entreprisesFti = FeatureTypeFactory.getFeatureByNameAndDatastore(
          CurrentAppFactory.appCfg.main.datastore,
          'kis_anc_demandeur'
        );

        /**
         * Get destination value
         */
        scope.getDestination = function() {
          if (
            !gaJsUtils.checkNestedProperty(scope.changeDestination, scope.cdata)
          ) {
            gaJsUtils.setNestedProperty(
              scope.changeDestination,
              scope.cdata,
              {}
            );
          }

          var name = scope.changeDestination + '.nom';
          var dest = name.split('.').reduce(index, scope.cdata);

          scope.value[name] = dest;
          scope.$emit('addDisplayDemandeur', {
            value: scope.changeDestination,
          });
        };

        // @RB getDestination() etait appelé via nginit et etait parfois lancé avant que le formulaire soit chargé
        if (angular.isDefined(scope.changeDestination)) {
          if (angular.isUndefined(scope.value)) scope.value = {};
          $timeout(function() {
            scope.getDestination();
          });
        }

        function index(obj, i) {
          return obj[i];
        }

        /**
         * Pick a person in the list
         */
        scope.chosirOrganisme = function() {
          var organisme = scope.selectedOrganisme.data[0];

          // mettre à jour le controle avec l'id du demandeur
          if (angular.isUndefined(scope.updatedb) || scope.updatedb === true)
            scope.$emit('ancControleDemandeurChoisi', {
              demandeur: organisme,
            });

          // update id dans données de la table
          // update informations demandeur
          if (angular.isDefined(scope.cdata)) {
            // Si type différent de demandeur, on crée l'objet dans le JSON
            if (angular.isDefined(scope.type)) {
              if (angular.isDefined(scope.changeDestination)) {
                for (var i in organisme.properties) {
                  gaJsUtils.setNestedProperty(
                    scope.changeDestination + '.' + i,
                    scope.cdata,
                    organisme.properties[i]
                  );
                  if (i === 'nom')
                    scope.value[scope.changeDestination + '.nom'] =
                      organisme.properties[i];
                }
              }
              if (
                !gaJsUtils.checkNestedProperty(
                  'info_generales.' + scope.type,
                  scope.cdata
                )
              )
                gaJsUtils.setNestedProperty(
                  'info_generales.' + scope.type,
                  scope.cdata,
                  {}
                );
              //if(!angular.isDefined(scope.cdata.info_generales[scope.type])) scope.cdata.info_generales[scope.type] = {};

              for (var i in organisme.properties) {
                scope.cdata.info_generales[scope.type][i] =
                  organisme.properties[i];
              }
            } else {
              if (!angular.isDefined(scope.cdata.info_generales.demandeur))
                scope.cdata.info_generales.demandeur = {};

              for (var i in organisme.properties) {
                scope.cdata.info_generales.demandeur[i] =
                  organisme.properties[i];
              }
            }
          } else {
            // todo if ever used ...
          }
          if (angular.isDefined(searchOrgaModal)) {
            searchOrgaModal.close();
          }
        };

        var getTypeFunc = function() {
          var getType;
          if (angular.isDefined(scope.entreprisesFti.attributes)) {
            scope.entreprisesFti.attributes.forEach(function(attr, i) {
              if (attr.name === 'type')
                getType = scope.entreprisesFti.attributes[i];
            });

            if (angular.isDefined(getType) && getType != null) {
              Object.keys(getType.restrictions[0].listofValues).forEach(
                function(type, i) {
                  if (
                    getType.restrictions[0].listofValues[type].toLowerCase() ==
                    scope.type
                  ) {
                    scope.typePosition = type;
                  }
                }
              );
            }
          }
        };

        var searchOrgaModal;
        /**
         * openSearchOrgaModal
         */
        scope.openSearchOrgaModal = function() {
          if (angular.isDefined(scope.type)) {
            if (angular.isUndefined(scope.typePosition)) getTypeFunc();
          }

          if (
            angular.isDefined(scope.typePosition) &&
            scope.typePosition != null
          ) {
            if (typeof userAndroid !== 'undefined') {
              scope.selectDemandeurFilter =
                "actif = 'true' AND nom <> '' AND nom IS NOT NULL AND type = " +
                scope.typePosition;
            } else {
              scope.selectDemandeurFilter =
                "actif = true AND nom <> '' AND nom IS NOT NULL AND type = " +
                scope.typePosition;
            }
          } else {
            if (typeof userAndroid !== 'undefined') {
              scope.selectDemandeurFilter =
                "actif = 'true' AND nom <> '' AND nom IS NOT NULL ";
            } else {
              scope.selectDemandeurFilter =
                "actif = true AND nom <> '' AND nom IS NOT NULL ";
            }
          }

          scope.selectedOrganisme = { data: [] };
          searchOrgaModal = ngDialog.open({
            template:
              'js/XG/widgets/ancapp/main/views/modals/modal.entreprise.search.html',
            className: 'ngdialog-theme-plain width800 miniclose nopadding',
            closeByDocument: false,
            scope: scope,
          });
        };

        var addOrgaModal;
        scope.openAddOrgaModal = function() {
          scope.demandeursFti = scope.entreprisesFti;
          scope.currentDemandeur = { data: [] };

          if (angular.isUndefined(scope.typePosition)) getTypeFunc();

          if (angular.isUndefined(scope.currentDemandeur.properties))
            scope.currentDemandeur.properties = {};

          if (
            angular.isUndefined(scope.currentDemandeur.properties.actif) ||
            scope.currentDemandeur.properties.actif == false
          )
            scope.currentDemandeur.properties.actif = true;

          scope.currentDemandeur.properties.type = scope.typePosition;

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

        scope.saveDemandeur = function() {
          var featureCollection = {
            type: 'FeatureCollection',
            features: [],
          };

          featureCollection.features.push({
            type: 'Feature',
            properties: scope.currentDemandeur.properties,
          });
          EditFactory.add(scope.entreprisesFti.uid, featureCollection).then(
            function(res) {
              require('toastr').success('Enregistré');
              scope.selectedOrganisme = { data: [] };
              scope.selectedOrganisme.data.push(
                JSON.parse(res.data.create[0].json)
              );
              scope.chosirOrganisme();

              addOrgaModal.close();
            }
          );
        };

        /**
         * unlinkDemandeur
         */
        scope.unlinkDemandeur = function() {
          if (angular.isDefined(scope.type)) {
            // if(angular.isDefined(scope.changeDestination))

            if (
              angular.isDefined(scope.cdata.info_generales[scope.type]) &&
              angular.isUndefined(scope.changeDestination)
            ) {
              //only delete, pas besoin de reset l'id_demandeur
              delete scope.cdata.info_generales[scope.type];
            } else if (angular.isDefined(scope.changeDestination)) {
              if (
                angular.isDefined(
                  gaJsUtils.checkNestedProperty(
                    scope.changeDestination,
                    scope.cdata
                  )
                )
              ) {
                gaJsUtils.setNestedProperty(
                  scope.changeDestination,
                  scope.cdata,
                  {}
                );
                delete scope.value[scope.changeDestination + '.nom'];
              }
            }
          }

          if (
            angular.isDefined(scope.cdata.info_generales.demandeur) &&
            angular.isUndefined(scope.changeDestination)
          ) {
            delete scope.cdata.info_generales.demandeur;
            // reset le demandeur
            scope.$emit('ancControleDemandeurReset', {});
          }
        };
        /**
         * demandeurNotSet
         */
        scope.demandeurNotSet = function() {
          if (
            angular.isDefined(scope.type) &&
            angular.isUndefined(scope.changeDestination)
          )
            return (
              !angular.isDefined(scope.cdata.info_generales) ||
              !angular.isDefined(scope.cdata.info_generales[scope.type]) ||
              !Object.keys(scope.cdata.info_generales[scope.type]).length
            );
          else if (
            angular.isDefined(scope.type) &&
            angular.isDefined(scope.changeDestination) &&
            scope.changeDestination != ''
          )
            return (
              !angular.isDefined(
                scope.value[scope.changeDestination + '.nom']
              ) ||
              !angular.isDefined(
                scope.value[scope.changeDestination + '.nom']
              ) ||
              !Object.keys(scope.value[scope.changeDestination + '.nom']).length
            );
          return (
            !angular.isDefined(scope.cdata.info_generales) ||
            !angular.isDefined(scope.cdata.info_generales.demandeur) ||
            !Object.keys(scope.cdata.info_generales.demandeur).length
          );
        };
      },
    };
  };

  ancBacDemandeurPicker.$inject = [
    'BacAppFactory',
    'AncAppFactory',
    'gaDomUtils',
    'ngDialog',
    'FeatureTypeFactory',
    'EditFactory',
    '$rootScope',
    'gaJsUtils',
    '$timeout',
  ];

  return ancBacDemandeurPicker;
});
