'use strict';
define(function() {
  var gcelement = function(
    $timeout,
    extendedNgDialog,
    ConfigFactory,
    $rootScope,
    AssociationFactory,
    gaJsUtils,
    $q,
    $filter
  ) {
    return {
      templateUrl: 'js/XG/widgets/utilities/select/views/gcselectsearchdata.html',
      restrict: 'E',
      scope: {
        result: '=res',
        geomSelect: '=?',
        formToOpen: '=?',
        formTitle: '=?',
        associations: '=?',
        templatefields: '=?',
        map: '=?',
        onfinish: '&',
      },
      /**
       * open 'recherche_donnees' form
       */
      link: function(scope) {

        /**
         * open a dialog containing a 'recherche_donnees'(searchData) form
         *
         * @param {*} formToOpen
         */
        scope.openDialogWithFormSearchData = function(formToOpen) {

          // hide this popup if we can
          if (scope.$parent.dlgPopup && scope.$parent.dlgPopup.features && typeof scope.$parent.dlgPopup.features.hide === 'function') {
            scope.$parent.dlgPopup.features.hide();
          } else {
            // dialog should be hidden but it can't because we don't have the reference to the dialog
            // propertie 'dlgPopup' should be defined in formRender and formFieldRender
            console.error('Impossible de masquer la fenêtre');
          }
          scope.preCloseCallbackExecuted = false;

          ConfigFactory.get(
            formToOpen.type,
            formToOpen.name + '.form'
          ).then((res) => {
            formToOpen.template = res.data;
            scope.currentlink = formToOpen;
            // generate child popup
            scope.dlgPopup =  extendedNgDialog.open({
              template:
                'js/XG/widgets/mapapp/interventionflow/views/formulaire_new.html',
              className:
                'ngdialog-theme-default ' +
                'height500' +
                ' nopadding miniclose interventionRenderWrapper',
              formOptions: res.data.options,
              closeByDocument: false,
              scope: scope,
              map: scope.map,
              associations: scope.associations,
              minimizeMaximize: true,
              scrollable: true,
              resizable: true,
              title: scope.formTitle,
              draggable: true,
              minWidth: '570px',
              minHeight: '400px',
              preCloseCallback: function() {
                //avoid callback to be called twice
                if (!scope.preCloseCallbackExecuted) {
                  let promises=[];
                  scope.preCloseCallbackExecuted = true;
                  if (scope.dlgPopup.scope.doSave && scope.dlgPopup.scope.featureToCopy) {
                    scope.result = scope.dlgPopup.scope.featureToCopy;
                    scope.geomSelect = scope.dlgPopup.scope.featureToCopy.geometry;
                    scope.associations = scope.dlgPopup.scope.associations;

                    if(gaJsUtils.notNullAndDefined([$rootScope.xgos, scope.result], 'portal.parameters.mainDB', true)
                        && typeof scope.result.id === 'string' && scope.result.id.includes('.')) {
                      const ftinames = [scope.result.id.split('.')[0], scope.templatefields.fti_info.name].join();

                      // KIS-3040: si le composant à copier ou le composant de destination
                      // ne possède aucune association, la récupération ne doit pas être lancée
                      let promise = AssociationFactory.allFeatureTypesAreAssociated($rootScope.xgos.portal.parameters.mainDB, ftinames).then(
                          res => {

                            // on lance la récupération également uniquement en présence d'association à charger (sinon getListObjectsCiblesToCopy plante)
                            if (typeof res.data === 'boolean' && res.data
                                && Array.isArray(scope.templatefields.association.associationToLoad)
                                && scope.templatefields.association.associationToLoad.length > 0) {
                              AssociationFactory.getListObjectsCiblesToCopy($rootScope.xgos.portal.parameters.mainDB,
                                  scope.templatefields.association.associationToLoad, scope.result.id,
                                  scope.templatefields.fti_info.name,true).then((res) => {
                                if (gaJsUtils.notNullAndDefined(scope.associations) &&
                                    scope.associations.features && scope.associations.features.length > 0) {
                                  scope.associations  = gaJsUtils.mergeTwoGetFeatResult(res.data, scope.associations);
                                } else {
                                  scope.associations = res.data;
                                }
                              },(err) => {a
                                require('toastr').error($filter('translate')(err.data));
                              });
                              promises.push(promise);
                            }
                          }
                      );
                    }
                  }
                  // execute on finish functions
                  $q.all(promises).then(()=>{
                    $timeout(scope.onfinish);
                    //re-display the parent popup
                    scope.$parent.dlgPopup.features.show();
                  }, error => {
                    console.error("Can't get associations objects");
                    if (error && typeof error.message === 'string') {
                      console.error(error.message);
                    }
                    scope.$parent.dlgPopup.features.show();
                  })
                }
              },
            });
          });
        };
      },
    };
  };

  gcelement.$inject = [
    '$timeout',
    'extendedNgDialog',
    'ConfigFactory',
    '$rootScope',
    'AssociationFactory',
    'gaJsUtils',
    '$q',
    '$filter'
  ];
  return gcelement;
});
