/**
 * A provider with common functions for ANC and BAC
 */
'use strict';
define(function () {
  return function () {
    this.$get = function (
      FeatureAttachmentFactory,
      FeatureTypeFactory,
      $filter
    ) {
      var ancBacTools = function () {
        this.openedControles = function (controles) {
          let openedControle = controles.find(function (element) {
            return element.properties.etat === 'ouvert';
          });
          return !angular.isUndefined(openedControle);
        };

        this.getCurrentDossierAttachmentsInfos = function (
          dossiers,
          selectedDossier
        ) {
          if (angular.isDefined(dossiers)) {
            let currentDossier = dossiers.find(function (element) {
              return element.id === selectedDossier.id;
            });
            if (angular.isDefined(currentDossier) 
            && angular.isDefined(currentDossier.properties) 
            && angular.isDefined(currentDossier.properties.attachmentsInfos)) {
              return currentDossier.properties.attachmentsInfos;
            }
            if (angular.isDefined(selectedDossier)) {
              if (
                angular.isUndefined(selectedDossier.properties.attachmentsInfos)
              ) {
                selectedDossier.properties.attachmentsInfos = null;
              }
              return selectedDossier.properties.attachmentsInfos;
            }
          }
          return null;
        };

        this.recalculateDocumentsNoforTab = function (
          dossiers,
          selectedDossier,
          tabs,
          sourceElements,
          tabIdentifier,
          tabTitle,
          attachmentsInfosVariable
        ) {
          let currentDossierAttachmentsInfos = this.getCurrentDossierAttachmentsInfos(
            dossiers,
            selectedDossier
          );
          if (
            angular.isDefined(sourceElements) &&
            currentDossierAttachmentsInfos !== null
          ) {
            currentDossierAttachmentsInfos[attachmentsInfosVariable + 'No'] = 0;
            sourceElements.forEach(function (item) {
              if (
                angular.isDefined(item.attachmentsNo) &&
                !isNaN(item.attachmentsNo)
              ) {
                currentDossierAttachmentsInfos[
                  attachmentsInfosVariable + 'No'
                ] += item.attachmentsNo;
                if (currentDossierAttachmentsInfos[attachmentsInfosVariable]) {
                  currentDossierAttachmentsInfos[attachmentsInfosVariable][
                    item.id
                  ] = item.attachmentsNo;
                }
              }
            });
            this.updateTabLabel(
              tabs,
              tabIdentifier,
              tabTitle,
              currentDossierAttachmentsInfos[attachmentsInfosVariable + 'No']
            );
          }
        };

        this.updateTabLabel = function (
          tabs,
          tabIdentifier,
          tabTitle,
          documentsNo
        ) {
          if (angular.isDefined(tabs)) {
            let tabElement = tabs.find(function (element) {
              return element.key === tabIdentifier;
            });
            if (angular.isDefined(tabElement)) {
              tabElement.title = tabTitle + ' (' + documentsNo + ')';
            }
          }
        };

        this.checkboxChanged = function (
          documents,
          featureId,
          document,
          isChecked
        ) {
          let documentCheckedForFeature = documents.find(
            (element) =>
              element.featureId === featureId && element.document === document
          );
          if (angular.isUndefined(documentCheckedForFeature) && isChecked) {
            documentCheckedForFeature = {
              featureId: featureId,
              document: document,
            };
            documents.push(documentCheckedForFeature);
          } else if (
            angular.isDefined(documentCheckedForFeature) &&
            !isChecked
          ) {
            let documentIndex = documents.indexOf(documentCheckedForFeature);
            if (documentIndex !== -1) {
              documents.splice(documentIndex, 1);
            }
          }
        };

        this.prepareDocumentsForMail = function (documentsInfos) {
          let metaInfo = [];
          documentsInfos.documentsCheckedForMail.forEach((documentElement) => {
            if (
              metaInfo.findIndex(
                (info) => info.featureId === documentElement.featureId
              ) < 0
            ) {
              let featureMetaInfo = {
                featureId: documentElement.featureId,
              };
              metaInfo.push(featureMetaInfo);
              documentsInfos.featureTypeInfos.forEach((featureTypeInfo) => {
                addMetaInfo(
                  featureMetaInfo,
                  documentElement.featureId,
                  featureTypeInfo
                );
              });
            }
          });

          let attachmentInfos = {
            metaInfo: metaInfo,
            documents: documentsInfos.documentsCheckedForMail,
          };
          FeatureAttachmentFactory.prepareMailAttachment(attachmentInfos)
            .then(function (response) {
              window.open(
                'mailto:' +
                  '?body=Les documents sont disponibles pour téléchargement ici : ' +
                  JSON.stringify(response.data),
                '_blank'
              );
            })
            .catch(function (error) {
              require('toastr').error(error);
            });

          function addMetaInfo(featureMetaInfo, featureId, featureTypeInfo) {
            if (featureId.startsWith(featureTypeInfo.featureType + '.')) {
              featureMetaInfo.folder = featureTypeInfo.folder;
              if (featureTypeInfo.hasSubfolders) {
                let featureInfos = featureTypeInfo.features.find(
                  (feature) => feature.attachmentData.id === featureId
                );
                featureMetaInfo.featureFolder = calculateFeatureFolder(
                  metaInfo,
                  featureInfos.label,
                  0
                );
              }
            }
          }

          function calculateFeatureFolder(
            metaInfo,
            featureFolder,
            folderIndex
          ) {
            let tempFeatureFolder =
              folderIndex === 0
                ? featureFolder
                : featureFolder + ' (' + folderIndex + ')';
            if (
              metaInfo.findIndex(
                (element) => element.featureFolder === tempFeatureFolder
              ) >= 0
            ) {
              return calculateFeatureFolder(
                metaInfo,
                featureFolder,
                folderIndex + 1
              );
            }
            return tempFeatureFolder;
          }
        };
        this.setDossierFullname = function (
          report,
          appType,
          initCopyReportButton,
          $location
        ) {
          var props = report.properties;
          var titre = 'Dossier <b>' + props.ref_dossier + '</b>';
          var fullAdresse = '';
          var _adprops = [
            'adresse_num_rue',
            'adresse_num_rue_extra',
            'adresse_rue',
            'adresse_batiment',
            'adresse_appt',
            'adresse_etage',
            'adresse_escalier',
            'adresse_complement',
            'adresse_cp',
            'adresse_ville',
            'adresse_bp',
            'adresse_pays',
          ];

          if (appType === 'anc') {
            // rdv
            if (
              angular.isDefined(report) &&
              props.date_prochain_controle != null
            ) {
              var typeC =
                props.prochain_controle != null ? props.prochain_controle : '';
              titre +=
                "<span class='reportTitleRDV'><i class='fa fa-calendar'></i> RDV " +
                typeC +
                ' le ' +
                $filter('date')(
                  props.date_prochain_controle,
                  'dd/MM/yyyy à HH:mm'
                ) +
                '</span>';
            }
          }
          // add address and proprietaire name to title
          fullAdresse = _adprops
            .map(function (x) {
              return props[x];
            })
            .join(' ')
            .trim();

          var hasAdresse = fullAdresse !== '';
          var hasProprios =
            props && props.proprietaires && props.proprietaires.length;
          var hasBoth = hasAdresse && hasProprios ? 'both' : '';

          if (hasAdresse !== '') {
            titre +=
              '<span class="rtextra reportTitleAdresse ' +
              hasBoth +
              '">' +
              fullAdresse +
              ' </span>';
          }
          if (hasProprios) {
            titre +=
              '<span class="rtextra reportTitleProprietaires ' +
              hasBoth +
              '">' +
              props.proprietaires
                .map(function (p) {
                  return p.nomComplet;
                })
                .join(' - ') +
              '</span>';
          }

          // bouton de permalien
          if (report.id) {
            if (!initCopyReportButton) {
              new Clipboard('.copyReportLink');
            }
            var copyReportUrl = $location.absUrl() + '&fid=' + report.id;
            titre =
              "<div class='copyReportLink'  data-clipboard-text='" +
              copyReportUrl +
              "' ng-click='notifyLinkCopy(\"dossier\")' title=\"Copier le lien d'accès direct à ce dossier\"><i class='fa fa-link'></i></div>" +
              titre;
          }
          return titre;
        };

        /**
         * attributeDisplayCondition
         * Choose to display attribute according to its prefix and display position
         * @attribute
         * @linkedTo (element|controle)
         */
        // used in modeles des elements de filiere
        this.attributeDisplayCondition = function (
          currentControle,
          allControles,
          attribute,
          linkedTo,
          withoutControle
        ) {
          var show = false;
          var beginByCtrl = new RegExp('^ctrl*');

          var objets = [];
          allControles.forEach(function (controle) {
            objets.push(controle.type);
          });

          var isControleAttribute = false;
          var isRelatedControleAttribute = false;
          objets.forEach(function (o) {
            var name = o.toLowerCase().replace('_mutation', '') + '_';
            var regex = new RegExp('^' + name + '*');
            if (
              !withoutControle &&
              (attribute.name.indexOf(name) === 0 ||
                attribute.name.indexOf('ctrl' + name) === 0)
            ) {
              isControleAttribute = true;
            }
            if (
              (attribute.name.indexOf(name) === 0 && currentControle === o) ||
              (attribute.name.indexOf('ctrl' + name) === 0 &&
                currentControle == o)
            ) {
              isRelatedControleAttribute = true;
            }
            if (
              attribute.name === 'caj_id_raccordement' ||
              attribute.name === 'caj_id_element_filiere'
            ) {
              linkedTo = '';
              show = false;
            }
          });

          //-- 'element': colonne de gauche
          //--    dans colonne de gauche pour FO1 uniquement attributs non préfixé ctrlfo1_
          //--    dans colonne de gauche pour les autres : tous les champs.
          if (
            linkedTo === 'element' &&
            ((allControles.length == 1 &&
              isControleAttribute &&
              allControles[0].type !== 'FO1') ||
              (!isControleAttribute && !beginByCtrl.test(attribute.name)))
          ) {
            show = true;
          }
          //-- 'controle': colonne de droite
          if (
            linkedTo === 'controle' &&
            isControleAttribute &&
            isRelatedControleAttribute
          ) {
            show = true;
          }

          return show;
        };

        this.copyAvisAgent = function (dataObject) {
          let avisAgentExists =
            angular.isDefined(dataObject.conformite.valeur_agent) &&
            dataObject.conformite.valeur_agent != null &&
            dataObject.conformite.valeur_agent.length > 0;
          let dateAgentExists =
            angular.isDefined(dataObject.datesDossier.date_avis_controleur) &&
            dataObject.datesDossier.date_avis_controleur != null &&
            dataObject.datesDossier.date_avis_controleur.length > 0;
          let commentAgentExists =
            angular.isDefined(dataObject.conformite.commentaire_agent) &&
            dataObject.conformite.commentaire_agent != null &&
            dataObject.conformite.commentaire_agent.length > 0;
          if (!avisAgentExists && !dateAgentExists && !commentAgentExists) {
            require('toastr').info(
              "Il n'y a pas des informations à copier",
              '',
              {
                positionClass: 'toast-bottom-left',
              }
            );
            return;
          }
          let message = '';
          let article = '';
          if (avisAgentExists) {
            message = "l'avis";
            article = 'celui';
          }
          if (dateAgentExists) {
            message +=
              (message.length > 0 ? (commentAgentExists ? ', ' : ' et ') : '') +
              'la date';
            article = article.length > 0 ? 'ceux' : 'celle';
          }
          if (commentAgentExists) {
            message += (message.length > 0 ? ' et ' : '') + 'le commentaire';
            article = article.length > 0 ? 'ceux' : 'celui';
          }
          var ans = confirm(
            'Êtes vous certain de vouloir copier ' +
              message +
              " de l'agent en lieu et place de " +
              article +
              ' du responsable ?'
          );
          if (ans) {
            if (avisAgentExists) {
              dataObject.conformite.valeur = dataObject.conformite.valeur_agent;
            }
            if (dateAgentExists) {
              dataObject.datesDossier.date_avis =
                dataObject.datesDossier.date_avis_controleur;
            }
            if (commentAgentExists) {
              dataObject.conformite.commentaire_responsable =
                dataObject.conformite.commentaire_agent;
            }
            require('toastr').success('Copie effectuée', '', {
              positionClass: 'toast-bottom-left',
            });
          }
        };

        this.getDossierExtraFields = function (datastore, apptype) {
          let extraFields = [];
          let dossierFTI = FeatureTypeFactory.getFeatureByNameAndDatastore(
            datastore,
            apptype === 'bac' ? 'kis_bac_dossier' : 'kis_anc_dossier'
          );
          if (
            angular.isDefined(dossierFTI) &&
            angular.isDefined(dossierFTI.attributes)
          ) {
            dossierFTI.attributes.forEach((attribute) => {
              if (attribute.name.startsWith('extra_')) {
                extraFields.push(attribute);
              }
            });
          }
          return extraFields;
        };
      };
      return new ancBacTools();
    };
    this.$get.$inject = [
      'FeatureAttachmentFactory',
      'FeatureTypeFactory',
      '$filter',
    ];
  };
});
