/**
   * To associate existing participant to the report and to create new SCG.
   *
   * @param request : request
   * @param reportQueueId : reportQueueId
   * @param participantIdToAssociate : participantIdToAssociate
   * @throws NumberFormatException : NumberFormatException
   * @throws BizLogicException : BizLogicException
   */
  private void createNewSCG(
      HttpServletRequest request, String reportQueueId, String participantIdToAssociate)
      throws NumberFormatException, BizLogicException {

    ReportLoaderQueue reportLoaderQueue = null;
    reportLoaderQueue = Utility.getReportQueueObject(reportQueueId);

    // Changing the status of the report in the queue to NEW
    reportLoaderQueue.setStatus(CaTIESConstants.NEW);

    // Create new SCG
    reportLoaderQueue.setSpecimenCollectionGroup(null);

    // removing all participants from CATISSUE_REPORT_PARTICIP_REL other
    // than the selected participant
    final Collection participantColl = reportLoaderQueue.getParticipantCollection();
    final Iterator iter = participantColl.iterator();
    final Set tempColl = new HashSet();
    while (iter.hasNext()) {
      final Participant participant = (Participant) iter.next();
      if (participant.getId().toString().equals(participantIdToAssociate.trim())) {
        tempColl.add(participant);
      }
    }
    reportLoaderQueue.setParticipantCollection(tempColl);

    // Updating the report queue obj
    this.updateReportLoaderQueue(reportLoaderQueue, request);
  }
  /**
   * Associate the existing SCG to the report.
   *
   * @param request : request
   * @param reportQueueId : reportQueueId
   * @param participantIdToAssociate : participantIdToAssociate
   * @param specimenCollGrpId : specimenCollGrpId
   * @throws DAOException : DAOException
   * @throws BizLogicException : BizLogicException
   * @throws UserNotAuthorizedException : UserNotAuthorizedException
   */
  private void associateSCGWithReport(
      HttpServletRequest request,
      String reportQueueId,
      String participantIdToAssociate,
      String specimenCollGrpId)
      throws DAOException, BizLogicException, UserNotAuthorizedException {
    Long cprId = null;
    ReportLoaderQueue reportLoaderQueue = null;
    reportLoaderQueue = Utility.getReportQueueObject(reportQueueId);

    // Changing the status of the report in the queue to NEW
    reportLoaderQueue.setStatus(CaTIESConstants.NEW);

    // Associating the SCG
    if (specimenCollGrpId != null && !specimenCollGrpId.equals("")) {
      SpecimenCollectionGroup scg = null;
      final IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory();
      final ReportLoaderQueueBizLogic reportLoaderQueueBizLogic =
          (ReportLoaderQueueBizLogic) factory.getBizLogic(ReportLoaderQueue.class.getName());
      final Object object =
          reportLoaderQueueBizLogic.retrieve(
              SpecimenCollectionGroup.class.getName(), new Long(specimenCollGrpId));
      if (object != null) {
        scg = (SpecimenCollectionGroup) object;
      }
      cprId = scg.getCollectionProtocolRegistration().getId();
      reportLoaderQueue.setSpecimenCollectionGroup(scg);
    }

    // Retrieving participantID if it is null
    if (participantIdToAssociate == null || participantIdToAssociate.equals("")) {
      final DefaultBizLogic defaultBizLogic = new DefaultBizLogic();
      final Long partID =
          (Long)
              defaultBizLogic.retrieveAttribute(
                  CollectionProtocolRegistration.class.getName(),
                  cprId,
                  Constants.COLUMN_NAME_PARTICIPANT_ID);
      participantIdToAssociate = partID.toString();
    }

    // removing all participants from CATISSUE_REPORT_PARTICIP_REL other
    // than the selected participant
    final Collection participantColl = reportLoaderQueue.getParticipantCollection();
    final Iterator iter = participantColl.iterator();
    final Set tempColl = new HashSet();
    Participant participant = null;
    while (iter.hasNext()) {
      participant = (Participant) iter.next();
      if (participant.getId().toString().equals(participantIdToAssociate.trim())) {
        tempColl.add(participant);
      }
    }
    reportLoaderQueue.setParticipantCollection(tempColl);

    // Updating the report queue obj
    this.updateReportLoaderQueue(reportLoaderQueue, request);
  }
  /**
   * updates Participant registration in CaTissue
   *
   * @param participant - Participant to be registered
   * @return instance of Participant
   * @throws ApplicationException - ApplicationException
   */
  public Participant updateParticipantRegistration(Participant participant)
      throws ApplicationException {
    if (participant == null || StringUtils.isEmpty(participant.getLastName())) {
      LOG.error(
          "Participant does not contain the unique medical identifier "
              + participant.getLastName());
      throw new ApplicationException("Participant does not contain the unique medical identifier");
    }

    final Participant existingParticipant =
        getParticipantForPatientId(
            participant.getLastName(), getShortTitleForParticipant(participant));
    if (existingParticipant == null) {
      LOG.error(
          "CaTissue does not contain a participant with the unique identifier, "
              + participant.getLastName());
      throw new ApplicationException(
          "CaTissue does not contain a participant with the unique identifier, "
              + participant.getLastName());
    }

    // check if the collection protocol is different, if different then throw exception
    if (isCollectionProtocolChanged(participant, existingParticipant)) {
      LOG.error(
          "Update Participant Registration failed for "
              + participant.getLastName()
              + "and exception is Study can't be changed while updating the Participant.");
      throw new ApplicationException(
          "Update Participant Registration failed for "
              + participant.getLastName()
              + "and exception is Study can't be changed while updating the Participant.");
    }

    participant.setId(existingParticipant.getId());

    // Set the values in CPR only for Create Participant Flow and don't set it for UpdateParticipant
    participant.setCollectionProtocolRegistrationCollection(
        new HashSet<CollectionProtocolRegistration>());

    // code to handle the existing/new race collection
    updateParticipantRaceCollection(existingParticipant, participant);

    try {
      caTissueAPIClient.update(participant);
    } catch (ApplicationException ae) {
      LOG.error(
          "Update Registration Failed for Participant with Subject ID " + participant.getLastName(),
          ae);
      throw new ApplicationException(ae);
    }

    return copyFrom(existingParticipant);
  }
  private Participant copyFrom(Participant participant) {
    final Participant p = ParticipantFactory.getInstance().createObject();

    p.setId(participant.getId());
    p.setActivityStatus(participant.getActivityStatus());
    p.setBirthDate(participant.getBirthDate());
    p.setEthnicity(participant.getEthnicity());
    p.setFirstName(participant.getFirstName());
    p.setLastName(participant.getLastName());
    p.setGender(participant.getGender());
    p.setMetaPhoneCode(participant.getMetaPhoneCode());
    p.setSocialSecurityNumber(participant.getSocialSecurityNumber());
    p.setVitalStatus(participant.getVitalStatus());

    final Iterator<Race> iter = participant.getRaceCollection().iterator();
    while (iter.hasNext()) {
      final Race race = (Race) iter.next();
      final Race r = RaceFactory.getInstance().createObject();
      r.setParticipant(p);
      r.setRaceName(race.getRaceName());
      p.getRaceCollection().add(r);
    }

    final Iterator<CollectionProtocolRegistration> cprIter =
        participant.getCollectionProtocolRegistrationCollection().iterator();
    while (cprIter.hasNext()) {
      final CollectionProtocolRegistration collectionProtocolRegistration =
          (CollectionProtocolRegistration) cprIter.next();

      final CollectionProtocol collectionProtocol =
          collectionProtocolRegistration.getCollectionProtocol();
      final CollectionProtocol cp = CollectionProtocolFactory.getInstance().createObject();
      cp.setActivityStatus(collectionProtocol.getActivityStatus());
      cp.setTitle(collectionProtocol.getTitle());
      cp.setShortTitle(collectionProtocol.getShortTitle());

      final CollectionProtocolRegistration cpr =
          CollectionProtocolRegistrationFactory.getInstance().createObject();
      cpr.setParticipant(p);
      cpr.setConsentSignatureDate(collectionProtocolRegistration.getConsentSignatureDate());
      cpr.setRegistrationDate(collectionProtocolRegistration.getRegistrationDate());
      cpr.setProtocolParticipantIdentifier(
          collectionProtocolRegistration.getProtocolParticipantIdentifier());
      // setting empty consenttier status collection, as update flow will not update consent tier
      cpr.setConsentTierResponseCollection(
          (Collection<ConsentTierResponse>) new LinkedHashSet<ConsentTierResponse>());

      cpr.setCollectionProtocol(cp);
      p.getCollectionProtocolRegistrationCollection().add(cpr);
    }
    return p;
  }