/**
   * Update the calculated person data. This method and updateCalculatedPersonOnDeleteOfSor need to
   * be generalized to handle recalculations.
   *
   * @param toPerson
   * @param fromPerson
   * @param sorPerson Adjust calculated roles... Point prc_role to prc_person receiving role Add the
   *     role to the set of roles in receiving prc_person Remove role from prc person losing role
   */
  protected void updateCalculatedPersonsOnMoveOfSor(
      final Person toPerson, final Person fromPerson, final SorPerson sorPerson) {
    Assert.notNull(toPerson, "toPerson cannot be null");
    Assert.notNull(fromPerson, "fromPerson cannot be null");
    logger.info("UpdateCalculated: recalculating person data for move.");

    final List<Role> rolesToDelete = new ArrayList<Role>();

    final List<SorRole> sorRoles = new ArrayList<SorRole>(sorPerson.getRoles());
    for (final SorRole sorRole : sorRoles) {
      for (final Role role : fromPerson.getRoles()) {
        if (sorRole.getId().equals(role.getSorRoleId())) {
          sorRoleElector.addSorRole(sorRole, toPerson);
          rolesToDelete.add(role);
        }
      }
    }
    for (final Role role : rolesToDelete) {
      sorRoleElector.removeCalculatedRole(
          fromPerson, role, this.personRepository.getSoRRecordsForPerson(fromPerson));
      fromPerson.getRoles().remove(role);
    }

    // TODO recalculate names for person receiving role? Anything else?
    // TODO recalculate names for person losing role? Anything else?
    //        this.personRepository.savePerson(fromPerson);
    //        this.personRepository.savePerson(toPerson);
  }
  public ServiceExecutionResult<SorRole> updateSorRole(
      final SorPerson sorPerson, final SorRole sorRole) {
    Assert.notNull(sorPerson, "sorPerson cannot be null.");
    Assert.notNull(sorRole, "sorRole cannot be null.");

    final Set validationErrors = this.validator.validate(sorRole);

    if (!validationErrors.isEmpty()) {
      // since because of existing design we cannot raise exception, we can only rollback the
      // transaction through code
      // OR-384
      if (TransactionAspectSupport.currentTransactionStatus() != null) {
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      }

      return new GeneralServiceExecutionResult<SorRole>(validationErrors);
    }

    final SorRole savedSorRole = this.personRepository.saveSorRole(sorRole);

    final Person person = this.personRepository.findByInternalId(sorPerson.getPersonId());
    final Role role = person.findRoleBySoRRoleId(savedSorRole.getId());
    if (role != null) {
      // update calculated role only if that role was previously converted to calculated one by
      // sorRoleElector
      role.recalculate(savedSorRole);
      this.personRepository.savePerson(person);
    }
    // else //do nothing i.e. don't update the calculated role if SorRoleElector Previously decided
    // not to convert this sor role to calculated role

    return new GeneralServiceExecutionResult<SorRole>(savedSorRole);
  }
  /**
   * Persists an SorPerson on update.
   *
   * @param sorPerson the person to update.
   * @return serviceExecutionResult.
   */
  public ServiceExecutionResult<SorPerson> updateSorPerson(final SorPerson sorPerson) {
    final Set validationErrors = this.validator.validate(sorPerson);

    if (!validationErrors.isEmpty()) {
      Iterator iter = validationErrors.iterator();
      while (iter.hasNext()) {
        logger.info("validation errors: " + iter.next());
      }
      // since because of existing design we cannot raise exception, we can only rollback the
      // transaction through code
      // OR-384
      if (TransactionAspectSupport.currentTransactionStatus() != null) {
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      }

      return new GeneralServiceExecutionResult<SorPerson>(validationErrors);
    }

    // do reconciliationCheck to make sure that modifications do not cause person to reconcile to a
    // different person
    if (!this.reconciler.reconcilesToSamePerson(sorPerson)) {
      throw new IllegalStateException();
    }

    // Iterate over any sorRoles setting sorid and source id if not specified by SoR.
    for (final SorRole sorRole : sorPerson.getRoles()) {
      setRoleIdAndSource(sorRole, sorPerson.getSourceSor());
    }

    // Save Sor Person
    final SorPerson savedSorPerson = this.personRepository.saveSorPerson(sorPerson);

    Person person = this.findPersonById(savedSorPerson.getPersonId());

    Assert.notNull(person, "person cannot be null.");

    logger.info(
        "Verifying Number of calculated Roles before the calculate: " + person.getRoles().size());

    // Iterate over sorRoles. SorRoles may be new or updated.
    for (final SorRole savedSorRole : savedSorPerson.getRoles()) {
      logger.info(
          "DefaultPersonService: savedSorPersonRole Found, savedSorRoleID: "
              + savedSorRole.getId());
      logger.info("DefaultPersonService: savedSorPersonRole Found, Role Must be newly added.");
      // let sor role elector decide if this new role can be converted to calculated one
      sorRoleElector.addSorRole(savedSorRole, person);
      logger.info(
          "Verifying Number of calculated Roles after calculate: " + person.getRoles().size());
    }

    for (final IdentifierAssigner ia : this.identifierAssigners) {
      ia.addIdentifierTo(sorPerson, person);
    }

    person = recalculatePersonBiodemInfo(person, savedSorPerson, RecalculationType.UPDATE, false);
    person = this.personRepository.savePerson(person);

    return new GeneralServiceExecutionResult<SorPerson>(savedSorPerson);
  }
  /**
   * This does not explicitly delete the names because its assumed the recalculation will clean it
   * up.
   */
  public boolean deleteSystemOfRecordPerson(
      final SorPerson sorPerson, final boolean mistake, final String terminationTypes) {
    Assert.notNull(sorPerson, "sorPerson cannot be null.");
    final String terminationTypeToUse =
        terminationTypes != null ? terminationTypes : Type.TerminationTypes.UNSPECIFIED.name();

    final Person person = this.personRepository.findByInternalId(sorPerson.getPersonId());
    Assert.notNull(person, "person cannot be null.");

    if (mistake) {
      Set<Role> rolesToDelete = new HashSet<Role>();

      for (final SorRole sorRole : sorPerson.getRoles()) {
        for (final Role role : person.getRoles()) {
          if (sorRole.getId().equals(role.getSorRoleId())) {
            rolesToDelete.add(role);
          }
        }
      }

      for (final Role role : rolesToDelete) {
        // let sorRoleElector delete the role and add another role if required
        sorRoleElector.removeCalculatedRole(
            person, role, this.personRepository.getSoRRecordsForPerson(person));
      }

      final Number number = this.personRepository.getCountOfSoRRecordsForPerson(person);

      if (number.intValue() == 1) {
        this.personRepository.deletePerson(person);
      }

      this.personRepository.deleteSorPerson(sorPerson);
      return true;
    }

    // we do this explicitly here because once they're gone we can't re-calculate?  We might move to
    // this to the recalculateCalculatedPerson method.
    final Type terminationReason =
        this.referenceRepository.findType(Type.DataTypes.TERMINATION, terminationTypeToUse);

    for (final SorRole sorRole : sorPerson.getRoles()) {
      for (final Role role : person.getRoles()) {
        if (!role.isTerminated() && sorRole.getId().equals(role.getSorRoleId())) {
          role.expireNow(terminationReason, true);
        }
      }
    }

    this.personRepository.deleteSorPerson(sorPerson);
    this.personRepository.savePerson(person);

    Person p = recalculatePersonBiodemInfo(person, sorPerson, RecalculationType.DELETE, mistake);
    this.personRepository.savePerson(p);
    return true;
  }
 /**
  * Move one Sor Record from one person to another where the to person is not in the registry
  *
  * @param fromPerson person losing sor record.
  * @param movingSorPerson record that is moving.
  * @return Success or failure.
  */
 public boolean moveSystemOfRecordPersonToNewPerson(Person fromPerson, SorPerson movingSorPerson) {
   Person savedPerson =
       recalculatePersonBiodemInfo(
           this.personObjectFactory.getObject(), movingSorPerson, RecalculationType.ADD, false);
   for (final IdentifierAssigner ia : this.identifierAssigners) {
     ia.addIdentifierTo(movingSorPerson, savedPerson);
   }
   // remove identifiers assigned to new person from old person
   fromPerson.getIdentifiers().removeAll(savedPerson.getIdentifiers());
   updateCalculatedPersonsOnMoveOfSor(savedPerson, fromPerson, movingSorPerson);
   fromPerson = this.personRepository.savePerson(fromPerson);
   savedPerson = this.personRepository.savePerson(savedPerson);
   movingSorPerson.setPersonId(savedPerson.getId());
   this.personRepository.saveSorPerson(movingSorPerson);
   return true;
 }
  /**
   * Current workflow for converting an SorPerson into the actual Person.
   *
   * @param reconciliationCriteria the original search criteria.
   * @return the newly saved Person.
   */
  protected Person saveSorPersonAndConvertToCalculatedPerson(
      final ReconciliationCriteria reconciliationCriteria) {
    if (!StringUtils.hasText(reconciliationCriteria.getSorPerson().getSorId())) {
      reconciliationCriteria.getSorPerson().setSorId(this.identifierGenerator.generateNextString());
    }

    logger.info("Executing new code!!!!!!");

    // Iterate over any sorRoles setting sorid and source id
    for (final SorRole sorRole : reconciliationCriteria.getSorPerson().getRoles()) {
      setRoleIdAndSource(sorRole, reconciliationCriteria.getSorPerson().getSourceSor());
    }

    logger.info(
        "Creating sorPerson: person_id: " + reconciliationCriteria.getSorPerson().getPersonId());
    // Save Sor Person
    final SorPerson sorPerson =
        this.personRepository.saveSorPerson(reconciliationCriteria.getSorPerson());
    Person savedPerson =
        recalculatePersonBiodemInfo(
            this.personObjectFactory.getObject(), sorPerson, RecalculationType.ADD, false);
    savedPerson = this.personRepository.savePerson(savedPerson);

    for (final IdentifierAssigner ia : this.identifierAssigners) {
      ia.addIdentifierTo(sorPerson, savedPerson);
    }
    idCardGenerator.addIDCard(savedPerson);

    // Create calculated roles.
    for (final SorRole newSorRole : sorPerson.getRoles()) {
      // let sor role elector decide if this new role can be converted to calculated one
      sorRoleElector.addSorRole(newSorRole, savedPerson);
    }

    final Person newPerson = this.personRepository.savePerson(savedPerson);

    logger.info("Verifying Number of calculated Roles: " + newPerson.getRoles().size());

    // Now connect the SorPerson to the actual person
    sorPerson.setPersonId(newPerson.getId());
    this.personRepository.saveSorPerson(sorPerson);
    logger.info("Created sorPerson: person_id: " + sorPerson.getPersonId());

    return newPerson;
  }
 /**
  * Move one Sor Record from one person to another.
  *
  * @param fromPerson person losing sor record.
  * @param toPerson person receiving sor record.
  * @return Success or failure.
  */
 public boolean moveSystemOfRecordPerson(
     Person fromPerson, Person toPerson, SorPerson movingSorPerson) {
   movingSorPerson.setPersonId(toPerson.getId());
   updateCalculatedPersonsOnMoveOfSor(toPerson, fromPerson, movingSorPerson);
   this.personRepository.savePerson(fromPerson);
   this.personRepository.savePerson(toPerson);
   this.personRepository.saveSorPerson(movingSorPerson);
   return true;
 }
  /**
   * Copy SorNames to Calculated Person
   *
   * @param person
   * @param sorPersons
   */
  protected void copySorNamesToPerson(final Person person, final List<SorPerson> sorPersons) {
    person.getNames().clear();

    for (final SorPerson sorPerson : sorPersons) {
      for (final SorName sorName : sorPerson.getNames()) {
        boolean alreadyAdded = false;

        for (final Name calculatedName : person.getNames()) {
          if (calculatedName.sameAs(sorName)) {
            alreadyAdded = true;
            break;
          }
        }

        if (!alreadyAdded) {
          person.addName(sorName);
        }
      }
    }
  }
  /**
   * Move All Sor Records from one person to another.
   *
   * @param fromPerson person losing sor records.
   * @param toPerson person receiving sor records.
   * @return Result of move. Validation errors if they occurred or the Person receiving sor records.
   */
  public boolean moveAllSystemOfRecordPerson(Person fromPerson, Person toPerson) {
    // get the list of sor person records that will be moving.
    List<SorPerson> sorPersonList = personRepository.getSoRRecordsForPerson(fromPerson);

    // move each sorRecord
    for (final SorPerson sorPerson : sorPersonList) {
      moveSystemOfRecordPerson(fromPerson, toPerson, sorPerson);
    }

    Set<? extends Identifier> oldIdentifiers = fromPerson.getIdentifiers();
    Set<? extends IdCard> oldIdCards = fromPerson.getIdCards();

    this.personRepository.deletePerson(fromPerson);
    logger.info("moveAllSystemOfRecordPerson: Deleted From Person");
    for (Identifier identifier : oldIdentifiers) {

      if (toPerson.getIdentifiersByType().get(identifier.getType().getName()) == null) {
        Identifier oldIdentifierAttachedTotoPerson =
            toPerson.addIdentifier(identifier.getType(), identifier.getValue());
        /// if type of this identifier don't exist then add this identifier as primary and not
        // deleted

        oldIdentifierAttachedTotoPerson.setDeleted(false);
        oldIdentifierAttachedTotoPerson.setPrimary(true);
      }
      // and if this exist then add this identifier as deleted and no primary
      else {
        Identifier oldIdentifierAttachedTotoPerson =
            toPerson.addIdentifier(identifier.getType(), identifier.getValue());
        /// if type of this identifier don't exist then add this identifier as primary and not
        // deleted

        oldIdentifierAttachedTotoPerson.setDeleted(true);
        oldIdentifierAttachedTotoPerson.setPrimary(false);
        ;
      }
    }
    for (IdCard oldIdCard : oldIdCards) {
      if (toPerson.getPrimaryIdCard() == null) {
        toPerson.addIDCard(oldIdCard);
      } else {
        if (oldIdCard.isPrimary()) oldIdCard.setPrimary(false);
        toPerson.addIDCard(oldIdCard);
      }
    }

    this.personRepository.savePerson(toPerson);

    return true;
  }
  public ServiceExecutionResult<Person> addPersonAndLink(
      final ReconciliationCriteria reconciliationCriteria, final Person person)
      throws IllegalArgumentException, IllegalStateException, SorPersonAlreadyExistsException {
    Assert.notNull(reconciliationCriteria, "reconciliationCriteria cannot be null.");
    Assert.notNull(person, "person cannot be null.");
    logger.info(" addPersonAndLink start");
    final ReconciliationResult result = this.criteriaCache.get(reconciliationCriteria);

    if (result == null) {
      throw new IllegalStateException("No ReconciliationResult found for provided criteria.");
    }

    for (final PersonMatch personMatch : result.getMatches()) {
      if (personMatch.getPerson().getId().equals(person.getId())) {
        addSorPersonAndLink(reconciliationCriteria, person);
        final Person savedPerson = this.personRepository.findByInternalId(person.getId());
        return new GeneralServiceExecutionResult<Person>(savedPerson);
      }
    }
    logger.info("addPersonAndLink end");
    throw new IllegalStateException("Person not found in ReconciliationResult.");
  }
  protected Person addSorPersonAndLink(
      final ReconciliationCriteria reconciliationCriteria, final Person person)
      throws SorPersonAlreadyExistsException {
    final SorPerson sorPerson = reconciliationCriteria.getSorPerson();
    final SorPerson registrySorPerson =
        this.findByPersonIdAndSorIdentifier(person.getId(), sorPerson.getSourceSor());

    if (registrySorPerson != null) {
      // throw new IllegalStateException("Oops! An error occurred. A person already exists from this
      // SoR linked to this ID!");
      throw new SorPersonAlreadyExistsException(registrySorPerson);
    }

    if (!StringUtils.hasText(sorPerson.getSorId())) {
      sorPerson.setSorId(this.identifierGenerator.generateNextString());
    }

    // Iterate over any sorRoles setting sorid and source id
    for (final SorRole sorRole : sorPerson.getRoles()) {
      setRoleIdAndSource(sorRole, sorPerson.getSourceSor());
    }

    sorPerson.setPersonId(person.getId());
    final SorPerson savedSorPerson = this.personRepository.saveSorPerson(sorPerson);

    // Create calculated roles.
    for (final SorRole newSorRole : savedSorPerson.getRoles()) {
      // let sor role elector decide if this new role can be converted to calculated one
      sorRoleElector.addSorRole(newSorRole, person);
    }

    // loop through all identifiers to see if addition of this new sor person will have a new
    // identifier created at calculated level
    for (final IdentifierAssigner ia : this.identifierAssigners) {
      ia.addIdentifierTo(sorPerson, person);
    }
    Person p = recalculatePersonBiodemInfo(person, savedSorPerson, RecalculationType.UPDATE, false);
    return this.personRepository.savePerson(p);
  }
  public boolean deleteSystemOfRecordRole(
      final SorPerson sorPerson,
      final SorRole sorRole,
      final boolean mistake,
      final String terminationTypes)
      throws IllegalArgumentException {
    Assert.notNull(sorRole, "sorRole cannot be null.");
    Assert.notNull(sorPerson, "soPerson cannot be null.");
    final String terminationTypeToUse =
        terminationTypes != null ? terminationTypes : Type.TerminationTypes.UNSPECIFIED.name();

    final Person person = this.personRepository.findByInternalId(sorPerson.getPersonId());
    Assert.notNull(person, "person cannot be null.");

    final Role role = person.findRoleBySoRRoleId(sorRole.getId());
    // delete and expire role only if it exist at calculated level
    if (role != null)
      if (mistake) {

        // let SorRoleElector remove the role
        sorRoleElector.removeCalculatedRole(
            person, role, this.personRepository.getSoRRecordsForPerson(person));

      } else {
        final Type terminationReason =
            this.referenceRepository.findType(Type.DataTypes.TERMINATION, terminationTypeToUse);
        if (!role.isTerminated()) {
          role.expireNow(terminationReason, true);
        }
      }

    sorPerson.getRoles().remove(sorRole);
    this.personRepository.saveSorPerson(sorPerson);
    this.personRepository.savePerson(person);
    return true;
  }
  protected Person recalculatePersonBiodemInfo(
      final Person person,
      final SorPerson sorPerson,
      final RecalculationType recalculationType,
      boolean mistake) {
    final List<SorPerson> sorPersons = this.personRepository.getSoRRecordsForPerson(person);
    logger.info("recalculatePersonBiodemInfo: start");
    if (recalculationType == RecalculationType.ADD
        || (recalculationType == RecalculationType.DELETE && !mistake)) {
      sorPersons.add(sorPerson);
    }

    copySorNamesToPerson(person, sorPersons);

    final Date birthDate =
        this.birthDateFieldElector.elect(
            sorPerson, sorPersons, recalculationType == RecalculationType.DELETE);
    final String gender =
        this.genderFieldElector.elect(
            sorPerson, sorPersons, recalculationType == RecalculationType.DELETE);
    final SorName preferredName =
        this.preferredNameFieldElector.elect(
            sorPerson, sorPersons, recalculationType == RecalculationType.DELETE);
    final SorName officialName =
        this.officialNameFieldElector.elect(
            sorPerson, sorPersons, recalculationType == RecalculationType.DELETE);
    final EmailAddress emailAddress =
        this.preferredContactEmailAddressFieldElector.elect(
            sorPerson, sorPersons, recalculationType == RecalculationType.DELETE);
    final Phone phone =
        this.preferredContactPhoneNumberFieldElector.elect(
            sorPerson, sorPersons, recalculationType == RecalculationType.DELETE);
    final Map<String, String> attributes =
        this.attributesElector.elect(
            sorPerson, sorPersons, recalculationType == RecalculationType.DELETE);
    final SorDisclosureSettings disclosure =
        this.disclosureFieldElector.elect(
            sorPerson, sorPersons, recalculationType == RecalculationType.DELETE);

    final String ssn =
        this.ssnFieldElector.elect(
            sorPerson, sorPersons, recalculationType == RecalculationType.DELETE);
    Identifier primarySSN = person.getPrimaryIdentifiersByType().get("SSN");
    // check if the elector elcted some ssn and person does have previous ssn assigned to it
    if (!org.apache.commons.lang.StringUtils.isEmpty(ssn) && primarySSN != null) {
      try {
        this.identifierChangeService.change(person.getPrimaryIdentifiersByType().get("SSN"), ssn);
      } catch (IllegalArgumentException e) {
        logger.debug(e.getStackTrace().toString());
      } // all other exception should be propogated
    }

    person.setDateOfBirth(birthDate);
    person.setGender(gender);
    person.getPreferredContactEmailAddress().update(emailAddress);
    person.getPreferredContactPhoneNumber().update(phone);
    person.calculateDisclosureSettings(disclosure);
    person.setAttributes(attributes);

    String affiliation = "";
    Type affiliationType = null;
    if (disclosure != null) {
      logger.info(
          "after person.calculateDisclosureSettings, disclosure code : "
              + disclosure.getDisclosureCode());
    } else {
      logger.info("Disclosure is null");
    }
    List<SorRole> sorroles = sorPerson.getRoles();
    for (SorRole role : sorroles) {
      if (role != null) {
        logger.info("Role = " + role.getTitle());
        if (role.getAffiliationType() != null) {
          logger.info("Role desc= " + role.getAffiliationType().getDescription());
          affiliation = role.getAffiliationType().getDescription();

          if (person.getDisclosureSettings() != null) {
            logger.info("recalculating disclosure setting 1...");
            // person.getDisclosureSettings().recalculate(this.strategyRepository.getDisclosureRecalculationStrategy());
            person
                .getDisclosureSettings()
                .recalculate(
                    this.strategyRepository.getDisclosureRecalculationStrategy(),
                    affiliation,
                    referenceRepository);
          }
        }
      }
    }

    // SSN election is happening in the ssn identifier assigner.

    boolean preferred = false;
    boolean official = false;

    for (final Name name : person.getNames()) {
      if (!preferred && name.sameAs(preferredName)) {
        name.setPreferredName(true);
        preferred = true;
      }

      if (!official && name.sameAs(officialName)) {
        name.setOfficialName(true);
        official = true;
      }

      if (official && preferred) {
        break;
      }
    }
    logger.info("recalculatePersonBiodemInfo: end");
    //        return this.personRepository.savePerson(person);
    return person;
  }