/*
   * Purpose: Iterates over ODM to populate 2 objects: 1. importCRFList: A List of EventCRFs and information on how to
   * process them. 2. importCRFMap: A Map multi-layer map of Subject/Event/Form only populated when the subsequent
   * EventCRF passes the UpsertOn rules.
   */
  public ImportCRFInfoContainer(ODMContainer odmContainer, DataSource ds) {
    importCRFList = new ArrayList<ImportCRFInfo>();

    ArrayList<EventCRFBean> eventCRFBeans = new ArrayList<EventCRFBean>();
    ArrayList<Integer> eventCRFBeanIds = new ArrayList<Integer>();
    EventCRFDAO eventCrfDAO = new EventCRFDAO(ds);
    StudySubjectDAO studySubjectDAO = new StudySubjectDAO(ds);
    StudyEventDefinitionDAO studyEventDefinitionDAO = new StudyEventDefinitionDAO(ds);
    StudyDAO studyDAO = new StudyDAO(ds);
    StudyEventDAO studyEventDAO = new StudyEventDAO(ds);
    UpsertOnBean upsert = odmContainer.getCrfDataPostImportContainer().getUpsertOn();
    // If Upsert bean is not present, create one with default settings
    if (upsert == null) upsert = new UpsertOnBean();
    String studyOID = odmContainer.getCrfDataPostImportContainer().getStudyOID();
    StudyBean studyBean = studyDAO.findByOid(studyOID);
    ArrayList<SubjectDataBean> subjectDataBeans =
        odmContainer.getCrfDataPostImportContainer().getSubjectData();

    Map<String, Map<String, Map<String, String>>> subjectMap =
        new HashMap<String, Map<String, Map<String, String>>>();
    for (SubjectDataBean subjectDataBean : subjectDataBeans) {
      ArrayList<StudyEventDataBean> studyEventDataBeans = subjectDataBean.getStudyEventData();
      StudySubjectBean studySubjectBean =
          studySubjectDAO.findByOidAndStudy(subjectDataBean.getSubjectOID(), studyBean.getId());

      Map<String, Map<String, String>> eventMap = new HashMap<String, Map<String, String>>();
      for (StudyEventDataBean studyEventDataBean : studyEventDataBeans) {
        ArrayList<FormDataBean> formDataBeans = studyEventDataBean.getFormData();
        String sampleOrdinal =
            studyEventDataBean.getStudyEventRepeatKey() == null
                ? "1"
                : studyEventDataBean.getStudyEventRepeatKey();

        StudyEventDefinitionBean studyEventDefinitionBean =
            studyEventDefinitionDAO.findByOidAndStudy(
                studyEventDataBean.getStudyEventOID(),
                studyBean.getId(),
                studyBean.getParentStudyId());
        logger.info(
            "find all by def and subject "
                + studyEventDefinitionBean.getName()
                + " study subject "
                + studySubjectBean.getName());

        StudyEventBean studyEventBean =
            (StudyEventBean)
                studyEventDAO.findByStudySubjectIdAndDefinitionIdAndOrdinal(
                    studySubjectBean.getId(),
                    studyEventDefinitionBean.getId(),
                    Integer.parseInt(sampleOrdinal));
        // @pgawade 16-March-2011 Do not allow the data import
        // if event status is one of the - stopped, signed,
        // locked
        Map<String, String> formMap = new HashMap<String, String>();
        for (FormDataBean formDataBean : formDataBeans) {

          CRFVersionDAO crfVersionDAO = new CRFVersionDAO(ds);
          ArrayList<CRFVersionBean> crfVersionBeans =
              crfVersionDAO.findAllByOid(formDataBean.getFormOID());
          for (CRFVersionBean crfVersionBean : crfVersionBeans) {

            ArrayList<EventCRFBean> eventCrfBeans =
                eventCrfDAO.findByEventSubjectVersion(
                    studyEventBean, studySubjectBean, crfVersionBean);
            // what if we have begun with creating a study
            // event, but haven't entered data yet? this would
            // have us with a study event, but no corresponding
            // event crf, yet.
            if (eventCrfBeans.isEmpty()) {
              logger.debug(
                  "   found no event crfs from Study Event id "
                      + studyEventBean.getId()
                      + ", location "
                      + studyEventBean.getLocation());

              ImportCRFInfo importCrfInfo =
                  new ImportCRFInfo(
                      studyOID,
                      subjectDataBean.getSubjectOID(),
                      studyEventDataBean.getStudyEventOID(),
                      formDataBean.getFormOID());
              importCrfInfo.setPreImportStage(DataEntryStage.UNCOMPLETED);
              String crfStatus = formDataBean.getEventCRFStatus();
              if (crfStatus != null
                  && crfStatus.equals(DataEntryStage.INITIAL_DATA_ENTRY.getName()))
                importCrfInfo.setPostImportStage(DataEntryStage.INITIAL_DATA_ENTRY);
              if ((studyEventBean.getSubjectEventStatus().equals(SubjectEventStatus.SCHEDULED)
                  || studyEventBean
                      .getSubjectEventStatus()
                      .equals(SubjectEventStatus.DATA_ENTRY_STARTED)
                  || studyEventBean.getSubjectEventStatus().equals(SubjectEventStatus.COMPLETED))) {

                if (!upsert.isNotStarted()) {
                  importCrfInfo.setProcessImport(false);
                  importCrfInfo.setEventCRFID(null);
                }
              }
              importCRFList.add(importCrfInfo);
              if (importCrfInfo.isProcessImport()) formMap.put(formDataBean.getFormOID(), "true");
            }

            for (EventCRFBean ecb : eventCrfBeans) {
              ImportCRFInfo importCrfInfo =
                  new ImportCRFInfo(
                      studyOID,
                      subjectDataBean.getSubjectOID(),
                      studyEventDataBean.getStudyEventOID(),
                      formDataBean.getFormOID());
              importCrfInfo.setPreImportStage(ecb.getStage());
              String crfStatus = formDataBean.getEventCRFStatus();
              if (crfStatus != null
                  && crfStatus.equals(DataEntryStage.INITIAL_DATA_ENTRY.getName()))
                importCrfInfo.setPostImportStage(DataEntryStage.INITIAL_DATA_ENTRY);
              importCrfInfo.setEventCRFID(new Integer(ecb.getId()));
              if (!(ecb.getStage().equals(DataEntryStage.INITIAL_DATA_ENTRY)
                      && upsert.isDataEntryStarted())
                  && !(ecb.getStage().equals(DataEntryStage.DOUBLE_DATA_ENTRY_COMPLETE)
                      && upsert.isDataEntryComplete())) importCrfInfo.setProcessImport(false);
              importCRFList.add(importCrfInfo);
              if (importCrfInfo.isProcessImport()) formMap.put(formDataBean.getFormOID(), "true");
            }
          }
        } // formdata loop
        if (formMap.size() > 0) eventMap.put(studyEventDataBean.getStudyEventOID(), formMap);
      } // study event loop
      if (eventMap.size() > 0) subjectMap.put(subjectDataBean.getSubjectOID(), eventMap);
    } // subject data loop
    importCRFMap = subjectMap;
  }
 public String generateHardValidationErrorMessage(
     ArrayList<SubjectDataBean> subjectData,
     HashMap<String, String> hardValidationErrors,
     boolean isValid) {
   StringBuffer sb = new StringBuffer();
   String studyEventRepeatKey = "1";
   String groupRepeatKey = "1";
   sb.append("<table border=\'0\' cellpadding=\'0\' cellspacing=\'0\' width=\'100%\'>");
   for (SubjectDataBean subjectDataBean : subjectData) {
     sb.append(
         "<tr valign=\'top\'> <td class=\'table_header_row\' colspan=\'4\'>Study Subject: "
             + subjectDataBean.getSubjectOID()
             + "</td> </tr>");
     // next step here
     ArrayList<StudyEventDataBean> studyEventDataBeans = subjectDataBean.getStudyEventData();
     for (StudyEventDataBean studyEventDataBean : studyEventDataBeans) {
       sb.append(
           "<tr valign=\'top\'> <td class=\'table_header_row\'>Event CRF OID</td> <td class=\'table_header_row\' colspan=\'3\'></td>");
       sb.append("</tr> <tr valign=\'top\'> <td class=\'table_cell_left\'>");
       sb.append(studyEventDataBean.getStudyEventOID());
       if (studyEventDataBean.getStudyEventRepeatKey() != null) {
         studyEventRepeatKey = studyEventDataBean.getStudyEventRepeatKey();
         sb.append(" (Repeat key " + studyEventDataBean.getStudyEventRepeatKey() + ")");
       } else {
         // reset
         studyEventRepeatKey = "1";
       }
       sb.append("</td> <td class=\'table_cell\' colspan=\'3\'></td> </tr>");
       ArrayList<FormDataBean> formDataBeans = studyEventDataBean.getFormData();
       for (FormDataBean formDataBean : formDataBeans) {
         sb.append("<tr valign=\'top\'> <td class=\'table_header_row\'></td> ");
         sb.append(
             "<td class=\'table_header_row\'>CRF Version OID</td> <td class=\'table_header_row\' colspan=\'2\'></td></tr>");
         sb.append(
             "<tr valign=\'top\'> <td class=\'table_cell_left\'></td> <td class=\'table_cell\'>");
         sb.append(formDataBean.getFormOID());
         sb.append("</td> <td class=\'table_cell\' colspan=\'2\'></td> </tr>");
         ArrayList<ImportItemGroupDataBean> itemGroupDataBeans = formDataBean.getItemGroupData();
         for (ImportItemGroupDataBean itemGroupDataBean : itemGroupDataBeans) {
           sb.append("<tr valign=\'top\'> <td class=\'table_header_row\'></td>");
           sb.append(
               "<td class=\'table_header_row\'></td> <td class=\'table_header_row\' colspan=\'2\'>");
           sb.append(itemGroupDataBean.getItemGroupOID());
           if (itemGroupDataBean.getItemGroupRepeatKey() != null) {
             groupRepeatKey = itemGroupDataBean.getItemGroupRepeatKey();
             sb.append(" (Repeat key " + itemGroupDataBean.getItemGroupRepeatKey() + ")");
           } else {
             groupRepeatKey = "1";
           }
           sb.append("</td></tr>");
           ArrayList<ImportItemDataBean> itemDataBeans = itemGroupDataBean.getItemData();
           for (ImportItemDataBean itemDataBean : itemDataBeans) {
             String oidKey =
                 itemDataBean.getItemOID()
                     + "_"
                     + studyEventRepeatKey
                     + "_"
                     + groupRepeatKey
                     + "_"
                     + subjectDataBean.getSubjectOID();
             if (!isValid) {
               if (hardValidationErrors.containsKey(oidKey)) {
                 sb.append("<tr valign=\'top\'> <td class=\'table_cell_left\'></td>");
                 sb.append(
                     "<td class=\'table_cell\'></td> <td class=\'table_cell\'><font color=\'red\'>");
                 sb.append(itemDataBean.getItemOID());
                 sb.append("</font></td> <td class=" + "\'table_cell\'>");
                 sb.append(itemDataBean.getValue() + "<br/>");
                 sb.append(hardValidationErrors.get(oidKey));
                 sb.append("</td></tr>");
                 /*
                  * <tr valign="top"> <td
                  * class="table_cell_left"></td> <td
                  * class="table_cell"></td> <td
                  * class="table_cell"><font
                  * color="red"><c:out
                  * value="${itemData.itemOID}"/></font></td>
                  * <td class="table_cell"> <c:out
                  * value="${itemData.value}"/><br/> <c:out
                  * value="${hardValidationErrors[oidKey]}"/>
                  * </td> </tr>
                  */
               }
             } else {
               if (!hardValidationErrors.containsKey(oidKey)) {
                 sb.append("<tr valign=\'top\'> <td class=\'table_cell_left\'></td>");
                 sb.append("<td class=\'table_cell\'></td> <td class=\'table_cell\'>");
                 sb.append(itemDataBean.getItemOID());
                 sb.append("</td> <td class=" + "\'table_cell\'>");
                 sb.append(itemDataBean.getValue());
                 sb.append("</td></tr>");
               }
             }
           }
         }
       }
     }
   }
   sb.append("</table>");
   return sb.toString();
 }