/**
  * Creates a minimal record
  *
  * @param orcidProfile The record to create
  * @return the new record
  */
 private OrcidProfile createMinimalProfile(OrcidProfile orcidProfile, boolean usedCaptcha) {
   OrcidProfile minimalProfile =
       orcidProfileManager.createOrcidProfile(orcidProfile, false, usedCaptcha);
   // Set source to the new email
   String sourceId = minimalProfile.getOrcidIdentifier().getPath();
   List<Email> emails = minimalProfile.getOrcidBio().getContactDetails().getEmail();
   for (Email email : emails) emailManager.addSourceToEmail(email.getValue(), sourceId);
   LOGGER.debug(
       "Created minimal orcid and assigned id of {}", orcidProfile.getOrcidIdentifier().getPath());
   return minimalProfile;
 }
  @Override
  public void sendDelegationRequestEmail(OrcidProfile managed, OrcidProfile trusted, String link) {
    // Create map of template params
    String orcid = managed.getOrcidIdentifier().getPath();
    Map<String, Object> templateParams = new HashMap<String, Object>();
    templateParams.put("baseUri", orcidUrlManager.getBaseUrl());
    templateParams.put("baseUriHttp", orcidUrlManager.getBaseUriHttp());
    templateParams.put("link", link);

    String trustedOrcidValue = trusted.retrieveOrcidPath();
    String managedOrcidValue = managed.retrieveOrcidPath();
    String emailNameForDelegate = deriveEmailFriendlyName(managed);
    String trustedOrcidName = deriveEmailFriendlyName(trusted);
    templateParams.put("emailNameForDelegate", emailNameForDelegate);
    templateParams.put("trustedOrcidName", trustedOrcidName);
    templateParams.put("trustedOrcidValue", trustedOrcidValue);
    templateParams.put("managedOrcidValue", managedOrcidValue);

    Email primaryEmail = managed.getOrcidBio().getContactDetails().retrievePrimaryEmail();
    if (primaryEmail == null) {
      LOGGER.info("Cant send admin delegate email if primary email is null: {}", orcid);
      return;
    }

    addMessageParams(templateParams, managed);

    String htmlBody =
        templateManager.processTemplate("admin_delegate_request_html.ftl", templateParams);

    // Send message
    if (apiRecordCreationEmailEnabled) {
      String subject = getSubject("email.subject.admin_as_delegate", managed, trustedOrcidName);
      ProfileEntity trustedProfileEntity = profileDao.find(trusted.getOrcidIdentifier().getPath());
      boolean notificationsEnabled =
          trustedProfileEntity != null ? trustedProfileEntity.getEnableNotifications() : false;
      if (notificationsEnabled) {
        NotificationCustom notification = new NotificationCustom();
        notification.setNotificationType(NotificationType.CUSTOM);
        notification.setSubject(subject);
        notification.setBodyHtml(htmlBody);
        createNotification(managed.getOrcidIdentifier().getPath(), notification);
      } else {
        mailGunManager.sendEmail(
            DELEGATE_NOTIFY_ORCID_ORG, primaryEmail.getValue(), subject, null, htmlBody);
      }
      profileEventDao.persist(
          new ProfileEventEntity(orcid, ProfileEventType.ADMIN_PROFILE_DELEGATION_REQUEST));
    } else {
      LOGGER.debug(
          "Not sending admin delegate email, because API record creation email option is disabled. Message would have been: {}",
          htmlBody);
    }
  }
 @Override
 public void resetUserPassword(String toEmail, OrcidProfile orcidProfile) {
   LOGGER.debug("Resetting password for Orcid: {}", orcidProfile.getOrcidIdentifier().getPath());
   if (!orcidProfile.getOrcidHistory().isClaimed()) {
     LOGGER.debug(
         "Profile is not claimed so re-sending claim email instead of password reset: {}",
         orcidProfile.getOrcidIdentifier().getPath());
     notificationManager.sendApiRecordCreationEmail(toEmail, orcidProfile);
   } else {
     notificationManager.sendPasswordResetEmail(toEmail, orcidProfile);
   }
 }
  @Override
  public void sendEmailAddressChangedNotification(OrcidProfile updatedProfile, Email oldEmail) {

    // build up old template
    Map<String, Object> templateParams = new HashMap<String, Object>();

    String subject = getSubject("email.subject.email_removed", updatedProfile);
    String email = oldEmail.getValue();
    String emailFriendlyName = deriveEmailFriendlyName(updatedProfile);
    templateParams.put("emailName", emailFriendlyName);
    String verificationUrl =
        createVerificationUrl(
            updatedProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue(),
            orcidUrlManager.getBaseUrl());
    templateParams.put("verificationUrl", verificationUrl);
    templateParams.put("oldEmail", oldEmail.getValue());
    templateParams.put(
        "newEmail",
        updatedProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue());
    templateParams.put("orcid", updatedProfile.getOrcidIdentifier().getPath());
    templateParams.put("baseUri", orcidUrlManager.getBaseUrl());
    templateParams.put("baseUriHttp", orcidUrlManager.getBaseUriHttp());
    templateParams.put("subject", subject);

    addMessageParams(templateParams, updatedProfile);

    // Generate body from template
    String body = templateManager.processTemplate("email_removed.ftl", templateParams);
    // Generate html from template
    String html = templateManager.processTemplate("email_removed_html.ftl", templateParams);

    mailGunManager.sendEmail(EMAIL_CHANGED_NOTIFY_ORCID_ORG, email, subject, body, html);
  }
  @Override
  public void sendPasswordResetEmail(String submittedEmail, OrcidProfile orcidProfile) {

    // Create map of template params
    Map<String, Object> templateParams = new HashMap<String, Object>();
    templateParams.put("emailName", deriveEmailFriendlyName(orcidProfile));
    templateParams.put("orcid", orcidProfile.getOrcidIdentifier().getPath());
    templateParams.put("subject", getSubject("email.subject.reset", orcidProfile));
    templateParams.put("baseUri", orcidUrlManager.getBaseUrl());
    templateParams.put("baseUriHttp", orcidUrlManager.getBaseUriHttp());
    // Generate body from template
    String resetUrl = createResetEmail(orcidProfile, orcidUrlManager.getBaseUrl());
    templateParams.put("passwordResetUrl", resetUrl);

    addMessageParams(templateParams, orcidProfile);

    // Generate body from template
    String body = templateManager.processTemplate("reset_password_email.ftl", templateParams);
    String htmlBody =
        templateManager.processTemplate("reset_password_email_html.ftl", templateParams);
    mailGunManager.sendEmail(
        RESET_NOTIFY_ORCID_ORG,
        submittedEmail,
        getSubject("email.subject.reset", orcidProfile),
        body,
        htmlBody);
  }
  public void sendVerificationReminderEmail(OrcidProfile orcidProfile, String email) {
    Map<String, Object> templateParams = new HashMap<String, Object>();

    String primaryEmail =
        orcidProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue();
    templateParams.put("primaryEmail", primaryEmail);
    String emailFriendlyName = deriveEmailFriendlyName(orcidProfile);
    templateParams.put("emailName", emailFriendlyName);
    String verificationUrl = createVerificationUrl(email, orcidUrlManager.getBaseUrl());
    templateParams.put("verificationUrl", verificationUrl);
    templateParams.put("orcid", orcidProfile.getOrcidIdentifier().getPath());
    templateParams.put("email", email);
    templateParams.put("subject", getSubject("email.subject.verify_reminder", orcidProfile));
    templateParams.put("baseUri", orcidUrlManager.getBaseUrl());
    templateParams.put("baseUriHttp", orcidUrlManager.getBaseUriHttp());

    addMessageParams(templateParams, orcidProfile);

    // Generate body from template
    String body =
        templateManager.processTemplate("verification_reminder_email.ftl", templateParams);
    String htmlBody =
        templateManager.processTemplate("verification_reminder_email_html.ftl", templateParams);
    mailGunManager.sendEmail(
        SUPPORT_VERIFY_ORCID_ORG,
        email,
        getSubject("email.subject.verify_reminder", orcidProfile),
        body,
        htmlBody);
  }
 public boolean sendServiceAnnouncement_1_For_2015(OrcidProfile orcidProfile) {
   String email = orcidProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue();
   String emailFriendlyName = deriveEmailFriendlyName(orcidProfile);
   Map<String, Object> templateParams = new HashMap<String, Object>();
   templateParams.put("emailName", emailFriendlyName);
   String verificationUrl = null;
   verificationUrl = createVerificationUrl(email, orcidUrlManager.getBaseUrl());
   boolean needsVerification =
       !orcidProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().isVerified()
           && orcidProfile.getType().equals(OrcidType.USER)
           && !orcidProfile.isDeactivated();
   if (needsVerification) {
     templateParams.put("verificationUrl", verificationUrl);
   }
   String emailFrequencyUrl =
       createUpdateEmailFrequencyUrl(
           orcidProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue());
   templateParams.put("emailFrequencyUrl", emailFrequencyUrl);
   templateParams.put("orcid", orcidProfile.getOrcidIdentifier().getPath());
   templateParams.put("baseUri", orcidUrlManager.getBaseUrl());
   addMessageParams(templateParams, orcidProfile);
   String subject =
       getSubject("email.service_announcement.subject.imporant_information", orcidProfile);
   String text =
       templateManager.processTemplate("service_announcement_1_2015.ftl", templateParams);
   String html =
       templateManager.processTemplate("service_announcement_1_2015_html.ftl", templateParams);
   boolean sent = mailGunManager.sendEmail("*****@*****.**", email, subject, text, html);
   return sent;
 }
  @Override
  public void sendOrcidDeactivateEmail(OrcidProfile orcidToDeactivate) {
    // Create verification url

    Map<String, Object> templateParams = new HashMap<String, Object>();

    String subject = getSubject("email.subject.deactivate", orcidToDeactivate);
    String email =
        orcidToDeactivate.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue();
    String encryptedEmail = encryptionManager.encryptForExternalUse(email);
    String base64EncodedEmail = Base64.encodeBase64URLSafeString(encryptedEmail.getBytes());
    String deactivateUrlEndpointPath = "/account/confirm-deactivate-orcid";

    String emailFriendlyName = deriveEmailFriendlyName(orcidToDeactivate);
    templateParams.put("emailName", emailFriendlyName);
    templateParams.put("orcid", orcidToDeactivate.getOrcidIdentifier().getPath());
    templateParams.put("baseUri", orcidUrlManager.getBaseUrl());
    templateParams.put("baseUriHttp", orcidUrlManager.getBaseUriHttp());
    templateParams.put(
        "deactivateUrlEndpoint", deactivateUrlEndpointPath + "/" + base64EncodedEmail);
    templateParams.put("deactivateUrlEndpointUrl", deactivateUrlEndpointPath);
    templateParams.put("subject", subject);

    addMessageParams(templateParams, orcidToDeactivate);

    // Generate body from template
    String body = templateManager.processTemplate("deactivate_orcid_email.ftl", templateParams);
    // Generate html from template
    String html =
        templateManager.processTemplate("deactivate_orcid_email_html.ftl", templateParams);

    mailGunManager.sendEmail(DEACTIVATE_NOTIFY_ORCID_ORG, email, subject, body, html);
  }
  @Override
  @Transactional
  public void sendNotificationToAddedDelegate(
      OrcidProfile orcidUserGrantingPermission, List<DelegationDetails> delegatesGrantedByUser) {
    // Create map of template params
    Map<String, Object> templateParams = new HashMap<String, Object>();
    String subject = getSubject("email.subject.added_as_delegate", orcidUserGrantingPermission);

    for (DelegationDetails newDelegation : delegatesGrantedByUser) {
      ProfileEntity delegateProfileEntity =
          profileDao.find(newDelegation.getDelegateSummary().getOrcidIdentifier().getPath());
      Boolean sendAdministrativeChangeNotifications =
          delegateProfileEntity.getSendAdministrativeChangeNotifications();
      if (sendAdministrativeChangeNotifications == null || !sendAdministrativeChangeNotifications) {
        LOGGER.debug(
            "Not sending added delegate email, because option to send administrative change notifications not set to true for delegate: {}",
            delegateProfileEntity.getId());
        return;
      }

      String grantingOrcidEmail =
          orcidUserGrantingPermission
              .getOrcidBio()
              .getContactDetails()
              .retrievePrimaryEmail()
              .getValue();
      String emailNameForDelegate = deriveEmailFriendlyName(delegateProfileEntity);
      String email = delegateProfileEntity.getPrimaryEmail().getId();

      templateParams.put("emailNameForDelegate", emailNameForDelegate);
      templateParams.put(
          "grantingOrcidValue", orcidUserGrantingPermission.getOrcidIdentifier().getPath());
      templateParams.put("grantingOrcidName", deriveEmailFriendlyName(orcidUserGrantingPermission));
      templateParams.put("baseUri", orcidUrlManager.getBaseUrl());
      templateParams.put("baseUriHttp", orcidUrlManager.getBaseUriHttp());
      templateParams.put("grantingOrcidEmail", grantingOrcidEmail);
      templateParams.put("subject", subject);

      addMessageParams(templateParams, orcidUserGrantingPermission);

      // Generate body from template
      String body = templateManager.processTemplate("added_as_delegate_email.ftl", templateParams);
      // Generate html from template
      String html =
          templateManager.processTemplate("added_as_delegate_email_html.ftl", templateParams);

      boolean notificationsEnabled = delegateProfileEntity.getEnableNotifications();
      if (notificationsEnabled) {
        NotificationCustom notification = new NotificationCustom();
        notification.setNotificationType(NotificationType.CUSTOM);
        notification.setSubject(subject);
        notification.setBodyHtml(html);
        createNotification(
            newDelegation.getDelegateSummary().getOrcidIdentifier().getPath(), notification);
      } else {
        mailGunManager.sendEmail(DELEGATE_NOTIFY_ORCID_ORG, email, subject, body, html);
      }
    }
  }
  @Override
  public void sendClaimReminderEmail(OrcidProfile orcidProfile, int daysUntilActivation) {
    // Create map of template params
    Map<String, Object> templateParams = new HashMap<String, Object>();
    templateParams.put("emailName", deriveEmailFriendlyName(orcidProfile));
    String orcid = orcidProfile.getOrcidIdentifier().getPath();
    templateParams.put("orcid", orcid);
    templateParams.put("subject", getSubject("email.subject.claim_reminder", orcidProfile));
    Source source = orcidProfile.getOrcidHistory().getSource();
    String creatorName = "";
    if (source != null) {
      if (source.getSourceName() != null && source.getSourceName().getContent() != null) {
        creatorName = source.getSourceName().getContent();
      } else {
        creatorName = source.retrieveSourcePath();
      }
    }
    templateParams.put("creatorName", creatorName);
    templateParams.put("baseUri", orcidUrlManager.getBaseUrl());
    templateParams.put("baseUriHttp", orcidUrlManager.getBaseUriHttp());
    templateParams.put("daysUntilActivation", daysUntilActivation);
    Email primaryEmail = orcidProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail();
    if (primaryEmail == null) {
      LOGGER.info("Cant send claim reminder email if primary email is null: {}", orcid);
      return;
    }
    String verificationUrl =
        createClaimVerificationUrl(primaryEmail.getValue(), orcidUrlManager.getBaseUrl());
    templateParams.put("verificationUrl", verificationUrl);

    addMessageParams(templateParams, orcidProfile);

    String email = orcidProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue();
    // Generate body from template
    String body = templateManager.processTemplate("claim_reminder_email.ftl", templateParams);
    String htmlBody =
        templateManager.processTemplate("claim_reminder_email_html.ftl", templateParams);

    // Send message
    if (apiRecordCreationEmailEnabled) {
      mailGunManager.sendEmail(
          CLAIM_NOTIFY_ORCID_ORG,
          email,
          getSubject("email.subject.claim_reminder", orcidProfile),
          body,
          htmlBody);
      profileEventDao.persist(new ProfileEventEntity(orcid, ProfileEventType.CLAIM_REMINDER_SENT));
    } else {
      LOGGER.debug(
          "Not sending claim reminder email, because API record creation email option is disabled. Message would have been: {}",
          body);
    }
  }
  @Override
  public void sendWelcomeEmail(OrcidProfile orcidProfile, String email) {
    Map<String, Object> templateParams = new HashMap<String, Object>();
    String subject = getSubject("email.subject.register.thanks", orcidProfile);
    String emailName = deriveEmailFriendlyName(orcidProfile);
    String verificationUrl = createVerificationUrl(email, orcidUrlManager.getBaseUrl());
    String orcidId = orcidProfile.getOrcidIdentifier().getPath();
    String baseUri = orcidUrlManager.getBaseUrl();
    String baseUriHttp = orcidUrlManager.getBaseUriHttp();

    templateParams.put("subject", subject);
    templateParams.put("emailName", emailName);
    templateParams.put("verificationUrl", verificationUrl);
    templateParams.put("orcidId", orcidId);
    templateParams.put("baseUri", baseUri);
    templateParams.put("baseUriHttp", baseUriHttp);

    SourceEntity source = sourceManager.retrieveSourceEntity();
    if (source != null) {
      String sourceId = source.getSourceId();
      String sourceName = source.getSourceName();
      // If the source is not the user itself
      if (sourceId != null && !sourceId.equals(orcidId)) {
        if (!PojoUtil.isEmpty(sourceName)) {
          String paramValue =
              " " + localeManager.resolveMessage("common.through") + " " + sourceName + ".";
          templateParams.put("source_name_if_exists", paramValue);
        } else {
          templateParams.put("source_name_if_exists", ".");
        }
      } else {
        templateParams.put("source_name_if_exists", ".");
      }
    } else {
      templateParams.put("source_name_if_exists", ".");
    }

    addMessageParams(templateParams, orcidProfile);

    // Generate body from template
    String body = templateManager.processTemplate("welcome_email.ftl", templateParams);
    // Generate html from template
    String html = templateManager.processTemplate("welcome_email_html.ftl", templateParams);

    mailGunManager.sendEmail(SUPPORT_VERIFY_ORCID_ORG, email, subject, body, html);
  }
  // look like the following is our best best for i18n emails
  // http://stackoverflow.com/questions/9605828/email-internationalization-using-velocity-freemarker-templates
  public boolean sendPrivPolicyEmail2014_03(OrcidProfile orcidProfile) {
    String email = orcidProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue();
    Map<String, Object> templateParams = new HashMap<String, Object>();

    String emailFriendlyName = deriveEmailFriendlyName(orcidProfile);
    templateParams.put("emailName", emailFriendlyName);
    if (!orcidProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().isVerified()) {
      String verificationUrl = createVerificationUrl(email, orcidUrlManager.getBaseUrl());
      templateParams.put("verificationUrl", verificationUrl);
    }
    templateParams.put("orcid", orcidProfile.getOrcidIdentifier().getPath());
    templateParams.put("baseUri", orcidUrlManager.getBaseUrl());
    templateParams.put("baseUriHttp", orcidUrlManager.getBaseUriHttp());

    addMessageParams(templateParams, orcidProfile);

    String text = templateManager.processTemplate("priv_policy_upate_2014_03.ftl", templateParams);
    String html =
        templateManager.processTemplate("priv_policy_upate_2014_03_html.ftl", templateParams);

    return mailGunManager.sendEmail(
        UPDATE_NOTIFY_ORCID_ORG, email, ORCID_PRIVACY_POLICY_UPDATES, text, html);
  }
  @Override
  @Transactional
  public void sendApiRecordCreationEmail(String toEmail, OrcidProfile createdProfile) {

    Source source = null;
    CustomEmailEntity customEmail = null;
    if (createdProfile.getOrcidHistory() != null
        && createdProfile.getOrcidHistory().getSource() != null) {
      if (!PojoUtil.isEmpty(createdProfile.getOrcidHistory().getSource().retrieveSourcePath())) {
        source = createdProfile.getOrcidHistory().getSource();
        customEmail =
            getCustomizedEmail(
                createdProfile.getOrcidHistory().getSource().retrieveSourcePath(), EmailType.CLAIM);
      }
    }

    String email =
        createdProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue().trim();
    String emailName = deriveEmailFriendlyName(createdProfile);
    String orcid = createdProfile.getOrcidIdentifier().getPath();
    String verificationUrl = createClaimVerificationUrl(email, orcidUrlManager.getBaseUrl());

    String creatorName = "";
    if (source != null) {
      if (source.getSourceName() != null && source.getSourceName().getContent() != null) {
        creatorName = source.getSourceName().getContent();
      } else if (!PojoUtil.isEmpty(source.retrieveSourcePath())) {
        creatorName = source.retrieveSourcePath();
      }
    }

    String subject = null;
    String body = null;
    String htmlBody = null;
    String sender = null;

    if (customEmail != null) {
      // Get the customized sender if available
      sender =
          PojoUtil.isEmpty(customEmail.getSender())
              ? CLAIM_NOTIFY_ORCID_ORG
              : customEmail.getSender();
      // Get the customized subject is available
      subject =
          PojoUtil.isEmpty(customEmail.getSubject())
              ? getSubject("email.subject.api_record_creation", createdProfile)
              : customEmail.getSubject();
      // Replace the wildcards
      subject = subject.replace(WILDCARD_USER_NAME, emailName);
      subject = subject.replace(WILDCARD_MEMBER_NAME, creatorName);
      if (customEmail.isHtml()) {
        htmlBody = customEmail.getContent();
        htmlBody = htmlBody.replace(WILDCARD_USER_NAME, emailName);
        htmlBody = htmlBody.replace(WILDCARD_MEMBER_NAME, creatorName);
        htmlBody = htmlBody.replace(EmailConstants.WILDCARD_VERIFICATION_URL, verificationUrl);
        if (htmlBody.contains(WILDCARD_WEBSITE) || htmlBody.contains(WILDCARD_DESCRIPTION)) {
          ClientDetailsEntity clientDetails = customEmail.getClientDetailsEntity();
          htmlBody = htmlBody.replace(WILDCARD_WEBSITE, clientDetails.getClientWebsite());
          htmlBody = htmlBody.replace(WILDCARD_DESCRIPTION, clientDetails.getClientDescription());
        }
      } else {
        body = customEmail.getContent();
        body = body.replace(WILDCARD_USER_NAME, emailName);
        body = body.replace(WILDCARD_MEMBER_NAME, creatorName);
        body = body.replace(EmailConstants.WILDCARD_VERIFICATION_URL, verificationUrl);
        if (body.contains(WILDCARD_WEBSITE) || body.contains(WILDCARD_DESCRIPTION)) {
          ClientDetailsEntity clientDetails = customEmail.getClientDetailsEntity();
          body = body.replace(WILDCARD_WEBSITE, clientDetails.getClientWebsite());
          body = body.replace(WILDCARD_DESCRIPTION, clientDetails.getClientDescription());
        }
      }
    } else {
      subject = getSubject("email.subject.api_record_creation", createdProfile);
      // Create map of template params
      Map<String, Object> templateParams = new HashMap<String, Object>();
      templateParams.put("emailName", emailName);
      templateParams.put("orcid", orcid);
      templateParams.put("subject", subject);
      templateParams.put("creatorName", creatorName);
      templateParams.put("baseUri", orcidUrlManager.getBaseUrl());
      templateParams.put("baseUriHttp", orcidUrlManager.getBaseUriHttp());
      templateParams.put("verificationUrl", verificationUrl);

      addMessageParams(templateParams, createdProfile);
      // Generate body from template
      body = templateManager.processTemplate("api_record_creation_email.ftl", templateParams);
      htmlBody =
          templateManager.processTemplate("api_record_creation_email_html.ftl", templateParams);
    }

    // Send message
    if (apiRecordCreationEmailEnabled) {
      boolean isCustomEmail = customEmail != null ? true : false;
      // TODO: How to handle sender? we might have to register them on
      // mailgun
      if (isCustomEmail) {
        mailGunManager.sendEmail(sender, email, subject, body, htmlBody, isCustomEmail);
      } else {
        mailGunManager.sendEmail(CLAIM_NOTIFY_ORCID_ORG, email, subject, body, htmlBody);
      }
    } else {
      LOGGER.debug(
          "Not sending API record creation email, because option is disabled. Message would have been: {}",
          body);
    }
  }
  @Override
  public void sendAmendEmail(
      OrcidProfile amendedProfile, AmendedSection amendedSection, Collection<Item> items) {
    String amenderOrcid = sourceManager.retrieveSourceOrcid();
    if (amenderOrcid == null) {
      LOGGER.debug("Not sending amend email, because amender is null: {}", amendedProfile);
      return;
    }
    if (amenderOrcid.equals(amendedProfile.getOrcidIdentifier().getPath())) {
      LOGGER.debug("Not sending amend email, because self edited: {}", amendedProfile);
      return;
    }
    SendChangeNotifications sendChangeNotifications =
        amendedProfile.getOrcidInternal().getPreferences().getSendChangeNotifications();
    if (sendChangeNotifications == null || !sendChangeNotifications.isValue()) {
      LOGGER.debug(
          "Not sending amend email, because option to send change notifications not set to true: {}",
          amendedProfile);
      return;
    }
    if (OrcidType.ADMIN.equals(profileDao.retrieveOrcidType(amenderOrcid))) {
      LOGGER.debug(
          "Not sending amend email, because modified by admin ({}): {}",
          amenderOrcid,
          amendedProfile);
      return;
    }

    String subject = getSubject("email.subject.amend", amendedProfile);

    // Create map of template params
    Map<String, Object> templateParams = new HashMap<String, Object>();
    templateParams.put("emailName", deriveEmailFriendlyName(amendedProfile));
    templateParams.put("orcid", amendedProfile.getOrcidIdentifier().getPath());
    templateParams.put("amenderName", extractAmenderName(amendedProfile, amenderOrcid));
    templateParams.put("baseUri", orcidUrlManager.getBaseUrl());
    templateParams.put("baseUriHttp", orcidUrlManager.getBaseUriHttp());
    templateParams.put("subject", subject);

    addMessageParams(templateParams, amendedProfile);

    // Generate body from template
    String body = templateManager.processTemplate("amend_email.ftl", templateParams);
    // Generate html from template
    String html = templateManager.processTemplate("amend_email_html.ftl", templateParams);

    boolean notificationsEnabled =
        profileDao.find(amendedProfile.getOrcidIdentifier().getPath()).getEnableNotifications();
    if (notificationsEnabled) {
      NotificationAmended notification = new NotificationAmended();
      notification.setNotificationType(NotificationType.AMENDED);
      notification.setAmendedSection(amendedSection);
      if (items != null) {
        notification.setItems(new Items(new ArrayList<>(items)));
      }
      createNotification(amendedProfile.getOrcidIdentifier().getPath(), notification);
    } else {
      String email =
          amendedProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue();
      mailGunManager.sendEmail(AMEND_NOTIFY_ORCID_ORG, email, subject, body, html);
    }
  }