/**
   * Soft deletes Participant in CaTissue. That is to mark it as disabled with SSN set as NULL.
   *
   * @param participant - Participant to be deleted
   * @return instance of Participant
   * @throws ApplicationException - ApplicationException
   */
  public Participant deleteParticipant(Participant participant) throws ApplicationException {
    final Participant persistedParticipant =
        getParticipantForPatientId(
            participant.getLastName(), getShortTitleForParticipant(participant));
    if (persistedParticipant == null) {
      return null;
    }

    persistedParticipant.setActivityStatus(DISABLED);
    persistedParticipant.setSocialSecurityNumber(null);
    persistedParticipant.setLastName(null);

    final Iterator<CollectionProtocolRegistration> iter =
        persistedParticipant.getCollectionProtocolRegistrationCollection().iterator();
    while (iter.hasNext()) {
      final CollectionProtocolRegistration collectionProtocolRegistration =
          (CollectionProtocolRegistration) iter.next();
      collectionProtocolRegistration.setProtocolParticipantIdentifier("");
      collectionProtocolRegistration.setActivityStatus(DISABLED);
      caTissueAPIClient.update(collectionProtocolRegistration);
    }

    /*
     * Iterator<ParticipantMedicalIdentifier> iter = persistedParticipant.getParticipantMedicalIdentifierCollection
     * ().iterator(); while (iter.hasNext()) { ParticipantMedicalIdentifier participantMedicalIdentifier =
     * (ParticipantMedicalIdentifier) iter .next();//caTissueAPIClient.delete(
     * "Delete from ParticipantMedicalIdentifier pmi where pmi.id=" + participantMedicalIdentifier.getId());
     * caTissueAPIClient.delete(participantMedicalIdentifier); }
     */

    persistedParticipant.getParticipantMedicalIdentifierCollection().clear();

    return caTissueAPIClient.update(persistedParticipant);
  }
 private String getShortTitleForParticipant(Participant participant) {
   String shortTitle = "";
   final ArrayList<CollectionProtocolRegistration> cprColl =
       new ArrayList<CollectionProtocolRegistration>(
           participant.getCollectionProtocolRegistrationCollection());
   if (!cprColl.isEmpty()) {
     // We are expecting only ONE CPR here
     final CollectionProtocolRegistration cpr = cprColl.get(0);
     final CollectionProtocol collectionProtocol = cpr.getCollectionProtocol();
     shortTitle = collectionProtocol.getShortTitle();
   }
   return shortTitle;
 }
  /**
   * This method is used to check if the CollectionProtocol of incoming participant is different
   * from existingParticipant
   *
   * @return true if the CP is different
   */
  private boolean isCollectionProtocolChanged(
      Participant participant, Participant existingParticipant) {
    boolean isCPChanged = false;
    final List<CollectionProtocolRegistration> existCPRList =
        new ArrayList<CollectionProtocolRegistration>(
            existingParticipant.getCollectionProtocolRegistrationCollection());
    final CollectionProtocolRegistration existCPR =
        (CollectionProtocolRegistration) existCPRList.get(0);
    final String existShortTitle = existCPR.getCollectionProtocol().getShortTitle();

    final ArrayList<CollectionProtocolRegistration> cprColl =
        new ArrayList<CollectionProtocolRegistration>(
            participant.getCollectionProtocolRegistrationCollection());
    final String shortTitle = cprColl.get(0).getCollectionProtocol().getShortTitle();
    if (!shortTitle.equals(existShortTitle)) {
      isCPChanged = true;
    }
    return isCPChanged;
  }
  /**
   * This method is used to populate the CP-title inside Participant object for given CP-shortTitle.
   * Also it will call method to populate the default ConsentTierResponse
   *
   * @param participant
   * @return Participant with Title populated
   * @throws ApplicationException - ApplicationException
   */
  private Participant populateCP(Participant participant) throws ApplicationException {
    final ArrayList<CollectionProtocolRegistration> cprColl =
        new ArrayList<CollectionProtocolRegistration>(
            participant.getCollectionProtocolRegistrationCollection());
    if (!cprColl.isEmpty()) {
      // We are expecting only ONE CPR here
      final CollectionProtocolRegistration incomingCPR = cprColl.get(0);
      final CollectionProtocol incomingCP = incomingCPR.getCollectionProtocol();

      // get the existing CollectionProtocol for given shortTitle
      final CollectionProtocol fetchedCP =
          getExistingCollectionProtocol(incomingCP.getShortTitle());

      if (fetchedCP != null) {
        // set the fetched CP_Title into the Participant-CPR-CP-title
        incomingCP.setTitle(fetchedCP.getTitle());

        populateConsentTierResponse(incomingCPR, fetchedCP);
      }
    }
    return participant;
  }
  private void populateConsentTierResponse(
      final CollectionProtocolRegistration incomingCPR, final CollectionProtocol fetchedCP)
      throws ApplicationException {
    final Collection<ConsentTier> consentTierCollection = fetchedCP.getConsentTierCollection();
    if (consentTierCollection == null || consentTierCollection.isEmpty()) {
      LOG.error("Collection Protocol's consent tier statements list is empty.");
      throw new ApplicationException(
          "Collection Protocol's consent tier statements list is empty.");
    }
    final Iterator<ConsentTier> it = consentTierCollection.iterator();

    while (it.hasNext()) {
      final ConsentTier consentTier = (ConsentTier) it.next();
      final ConsentTierResponse ctResp = ConsentTierResponseFactory.getInstance().createObject();
      ctResp.setConsentTier(consentTier);
      ctResp.setResponse(NOT_SPECIFIED);
      incomingCPR.getConsentTierResponseCollection().add(ctResp);
    }
  }
  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;
  }
  private void createSCGUnderCPHavingScientistAsPI() {
    try {
      CollectionProtocol cp = new CollectionProtocol();
      cp.setId(new Long(BizTestCaseUtility.CP_WITH_SCIENTIST_AS_PI));
      Participant participant = BaseTestCaseUtility.initParticipant();
      participant.setSocialSecurityNumber("111-22-3233");
      try {
        participant.setBirthDate(
            Utility.parseDate("05-02-1984", CommonServiceLocator.getInstance().getDatePattern()));
      } catch (ParseException e) {
        Logger.out.debug("" + e);
      }
      System.out.println("Participant" + participant);
      SessionDataBean bean = (SessionDataBean) getSession().getAttribute("sessionData");
      try {
        participant = (Participant) appService.createObject(participant);
      } catch (Exception e) {
        e.printStackTrace();
        assertFalse(e.getMessage(), true);
      }
      BizTestCaseUtility.setNameObjectMap("ParticipantWithScientistAsPI", participant);
      CollectionProtocolRegistration collectionProtocolRegistration =
          new CollectionProtocolRegistration();

      collectionProtocolRegistration.setCollectionProtocol(cp);
      collectionProtocolRegistration.setParticipant(participant);
      collectionProtocolRegistration.setProtocolParticipantIdentifier("");
      collectionProtocolRegistration.setActivityStatus("Active");

      try {
        collectionProtocolRegistration.setRegistrationDate(
            Utility.parseDate("08/15/2006", Utility.datePattern("08/15/2006")));

        collectionProtocolRegistration.setConsentSignatureDate(
            Utility.parseDate("11/23/2006", Utility.datePattern("11/23/2006")));
        System.out.println("Creating CPR");
      } catch (ParseException e) {
        e.printStackTrace();
      }

      collectionProtocolRegistration.setSignedConsentDocumentURL("F:/doc/consentDoc.doc");

      User user = new User();
      user.setId(new Long(1));

      collectionProtocolRegistration.setConsentWitness(user);

      //				Collection consentTierResponseCollection = new LinkedHashSet();
      //				Collection consentTierCollection = new LinkedHashSet();
      //
      //				consentTierCollection = cp.getConsentTierCollection();
      //				System.out.println("Creating CPR");
      //				Iterator consentTierItr = consentTierCollection.iterator();
      //				System.out.println("Creating CPR");
      //				 while(consentTierItr.hasNext())
      //				 {
      //					 ConsentTier consent= (ConsentTier) consentTierItr.next();
      //					 ConsentTierResponse response= new ConsentTierResponse();
      //					 response.setResponse("Yes");
      //					 response.setConsentTier(consent);
      //					 consentTierResponseCollection.add(response);
      //				 }
      //
      //
      //	collectionProtocolRegistration.setConsentTierResponseCollection(consentTierResponseCollection);
      try {
        collectionProtocolRegistration =
            (CollectionProtocolRegistration)
                appService.createObject(collectionProtocolRegistration);
      } catch (Exception e) {
        Logger.out.error(e.getMessage(), e);
        e.printStackTrace();
        assertFalse(e.getMessage(), true);
      }
      BizTestCaseUtility.setNameObjectMap("CPRWithScientistAsPI", collectionProtocolRegistration);

      SpecimenCollectionGroup scg = new SpecimenCollectionGroup();

      scg = (SpecimenCollectionGroup) BaseTestCaseUtility.createSCG(collectionProtocolRegistration);
      Site site = new Site();
      site.setId(new Long(BizTestCaseUtility.CP_WITH_ALLOW_READ_PRIV));
      scg.setSpecimenCollectionSite(site);
      scg.setName("New SCG" + UniqueKeyGeneratorUtil.getUniqueKey());
      scg = (SpecimenCollectionGroup) BaseTestCaseUtility.setEventParameters(scg);
      scg.setSurgicalPathologyNumber("SPN" + UniqueKeyGeneratorUtil.getUniqueKey());
      System.out.println("Creating SCG");

      try {
        scg = (SpecimenCollectionGroup) appService.createObject(scg);
        System.out.println("SCG::" + scg.getName());
      } catch (Exception e) {
        Logger.out.error(e.getMessage(), e);
        e.printStackTrace();
        assertFalse(e.getMessage(), true);
      }

      IdentifiedSurgicalPathologyReport identifiedSurgicalPathologyReport =
          new IdentifiedSurgicalPathologyReport();
      identifiedSurgicalPathologyReport.setActivityStatus(Status.ACTIVITY_STATUS_ACTIVE.toString());
      identifiedSurgicalPathologyReport.setCollectionDateTime(new Date());
      identifiedSurgicalPathologyReport.setIsFlagForReview(new Boolean(false));
      identifiedSurgicalPathologyReport.setReportStatus(CaTIESConstants.PENDING_FOR_DEID);
      identifiedSurgicalPathologyReport.setReportSource(site);
      TextContent textContent = new TextContent();
      String data =
          "[FINAL DIAGNOSIS]\n"
              + "This is the Final Diagnosis Text"
              + "\n\n[GROSS DESCRIPTION]"
              + "The specimen is received unfixed labeled hernia sac and consists of a soft, pink to yellow segment of fibrous and fatty tissue measuring 7.5cm in length x 3.2 x 0.9cm with a partly defined lumen.  Representative tissue submitted labeled 1A.";

      textContent.setData(data);
      textContent.setSurgicalPathologyReport(identifiedSurgicalPathologyReport);
      Set reportSectionCollection = new HashSet();
      ReportSection reportSection1 = new ReportSection();
      reportSection1.setName("GDT");
      reportSection1.setDocumentFragment(
          "The specimen is received unfixed labeled hernia sac and consists of a soft, pink to yellow segment of fibrous and fatty tissue measuring 7.5cm in length x 3.2 x 0.9cm with a partly defined lumen.  Representative tissue submitted labeled 1A.");
      reportSection1.setTextContent(textContent);

      ReportSection reportSection2 = new ReportSection();
      reportSection2.setName("FIN");
      reportSection2.setDocumentFragment("This is the Final Diagnosis Text");
      reportSection2.setTextContent(textContent);

      reportSectionCollection.add(reportSection1);
      reportSectionCollection.add(reportSection2);

      textContent.setReportSectionCollection(reportSectionCollection);

      identifiedSurgicalPathologyReport.setTextContent(textContent);
      identifiedSurgicalPathologyReport.setSpecimenCollectionGroup(scg);
      scg.setSurgicalPathologyNumber("SPN" + UniqueKeyGeneratorUtil.getUniqueKey());

      try {
        identifiedSurgicalPathologyReport =
            (IdentifiedSurgicalPathologyReport)
                appService.createObject(identifiedSurgicalPathologyReport);
      } catch (Exception e) {
        Logger.out.error(e.getMessage(), e);
        e.printStackTrace();
        assertFalse(e.getMessage(), true);
      }
      BizTestCaseUtility.setObjectMap(
          identifiedSurgicalPathologyReport, IdentifiedSurgicalPathologyReport.class);

      BizTestCaseUtility.setNameObjectMap("SCGWithScientistAsPI", scg);
      //				TissueSpecimen specimenObj = (TissueSpecimen) BaseTestCaseUtility.initTissueSpecimen();
      //				specimenObj.setSpecimenCollectionGroup(scg);
      //				StorageContainer sc = new StorageContainer();
      //				sc.setId(new Long(1));
      //				specimenObj.setStorageContainer(sc);
      //				specimenObj.setPositionDimensionOne(new Integer(3));
      //				specimenObj.setPositionDimensionTwo(new Integer(1));
      //				try{
      //					specimenObj =  (TissueSpecimen) appService.createObject(specimenObj);
      //					System.out.println("Mol Specimen:"+ specimenObj.getLabel());
      //				}
      //				catch(Exception e){
      //					Logger.out.error(e.getMessage(),e);
      //		           	e.printStackTrace();
      //		           	assertFalse("Failed to register participant", true);
      //				}
    } catch (Exception e) {
      Logger.out.error(e.getMessage(), e);
      e.printStackTrace();
      assertFalse(e.getMessage(), true);
    }
  }