/**
   * This method creates a List of DisplaySectionBeans, returning them in the order that the
   * sections appear in a CRF. This List is "lazily" initialized the first time it is requested.
   *
   * @return A List of DisplaySectionBeans.
   * @see org.akaza.openclinica.control.managestudy.PrintCRFServlet
   * @see org.akaza.openclinica.control.managestudy.PrintDataEntryServlet
   */
  public List<DisplaySectionBean> getDisplaySectionBeans() {
    FormBeanUtil formBeanUtil;
    ViewPersistanceHandler persistanceHandler;
    ArrayList<SectionBean> allCrfSections;
    // DAO classes for getting item definitions
    SectionDAO sectionDao;
    CRFVersionDAO crfVersionDao;

    if (displaySectionBeans == null) {
      displaySectionBeans = new ArrayList<DisplaySectionBean>();
      formBeanUtil = new FormBeanUtil();
      if (hasStoredData) persistanceHandler = new ViewPersistanceHandler();

      // We need a CRF version id to populate the form display
      if (this.crfVersionId == 0) {
        return displaySectionBeans;
      }

      sectionDao = new SectionDAO(dataSource);
      allCrfSections = (ArrayList) sectionDao.findByVersionId(this.crfVersionId);

      // for the purposes of null values, try to obtain a valid
      // eventCrfDefinition id
      EventDefinitionCRFBean eventDefBean = null;
      EventCRFBean eventCRFBean = new EventCRFBean();
      if (eventCRFId > 0) {
        EventCRFDAO ecdao = new EventCRFDAO(dataSource);
        eventCRFBean = (EventCRFBean) ecdao.findByPK(eventCRFId);
        StudyEventDAO sedao = new StudyEventDAO(dataSource);
        StudyEventBean studyEvent = (StudyEventBean) sedao.findByPK(eventCRFBean.getStudyEventId());

        EventDefinitionCRFDAO eventDefinitionCRFDAO = new EventDefinitionCRFDAO(dataSource);
        StudyDAO sdao = new StudyDAO(dataSource);
        StudyBean study = sdao.findByStudySubjectId(eventCRFBean.getStudySubjectId());
        eventDefBean =
            eventDefinitionCRFDAO.findByStudyEventIdAndCRFVersionId(
                study, studyEvent.getId(), this.crfVersionId);
      }
      eventDefBean = eventDefBean == null ? new EventDefinitionCRFBean() : eventDefBean;
      // Create an array or List of DisplaySectionBeans representing each
      // section
      // for printing
      DisplaySectionBean displaySectionBean;
      for (SectionBean sectionBean : allCrfSections) {
        displaySectionBean =
            formBeanUtil.createDisplaySectionBWithFormGroups(
                sectionBean.getId(),
                this.crfVersionId,
                dataSource,
                eventDefBean.getId(),
                eventCRFBean,
                context);
        displaySectionBeans.add(displaySectionBean);
      }
    }
    return displaySectionBeans;
  }
  @Override
  public void processRequest() throws Exception {

    CRFVersionDAO cvdao = new CRFVersionDAO(sm.getDataSource());
    FormProcessor fp = new FormProcessor(request);
    int versionId = fp.getInt("id", true);
    String module = fp.getString("module");
    request.setAttribute("module", module);

    String action = fp.getString("action");
    if (versionId == 0) {
      addPageMessage(respage.getString("please_choose_a_CRF_version_to_remove"));
      forwardPage(Page.CRF_LIST_SERVLET);
    } else {
      if (StringUtil.isBlank(action)) {
        addPageMessage(respage.getString("no_action_specified"));
        forwardPage(Page.CRF_LIST_SERVLET);
        return;
      }
      CRFVersionBean version = (CRFVersionBean) cvdao.findByPK(versionId);

      SectionDAO secdao = new SectionDAO(sm.getDataSource());

      EventCRFDAO evdao = new EventCRFDAO(sm.getDataSource());
      // find all event crfs by version id
      ArrayList eventCRFs = evdao.findUndeletedWithStudySubjectsByCRFVersion(versionId);
      if ("confirm".equalsIgnoreCase(action)) {
        request.setAttribute("versionToRemove", version);
        request.setAttribute("eventCRFs", eventCRFs);
        forwardPage(Page.REMOVE_CRF_VERSION);
      } else {
        logger.info("submit to remove the crf version");
        // version
        version.setStatus(Status.DELETED);
        version.setUpdater(ub);
        version.setUpdatedDate(new Date());
        cvdao.update(version);
        // added below tbh 092007, seems that we don't remove the event
        // crfs in the second pass
        for (int ii = 0; ii < eventCRFs.size(); ii++) {
          EventCRFBean ecbean = (EventCRFBean) eventCRFs.get(ii);
          ecbean.setStatus(Status.AUTO_DELETED);
          ecbean.setUpdater(ub);
          ecbean.setUpdatedDate(new Date());
          evdao.update(ecbean);
        }
        // added above tbh 092007, to fix task
        // all sections
        ArrayList sections = secdao.findAllByCRFVersionId(version.getId());
        for (int j = 0; j < sections.size(); j++) {
          SectionBean section = (SectionBean) sections.get(j);
          if (!section.getStatus().equals(Status.DELETED)) {
            section.setStatus(Status.AUTO_DELETED);
            section.setUpdater(ub);
            section.setUpdatedDate(new Date());
            secdao.update(section);
          }
        }

        // all item data related to event crfs
        ItemDataDAO idao = new ItemDataDAO(sm.getDataSource());
        for (int i = 0; i < eventCRFs.size(); i++) {
          EventCRFBean eventCRF = (EventCRFBean) eventCRFs.get(i);
          if (!eventCRF.getStatus().equals(Status.DELETED)) {
            eventCRF.setStatus(Status.AUTO_DELETED);
            eventCRF.setUpdater(ub);
            eventCRF.setUpdatedDate(new Date());
            evdao.update(eventCRF);

            ArrayList items = idao.findAllByEventCRFId(eventCRF.getId());
            for (int j = 0; j < items.size(); j++) {
              ItemDataBean item = (ItemDataBean) items.get(j);
              if (!item.getStatus().equals(Status.DELETED)) {
                item.setStatus(Status.AUTO_DELETED);
                item.setUpdater(ub);
                item.setUpdatedDate(new Date());
                idao.update(item);
              }
            }
          }
        }

        addPageMessage(
            respage.getString("the_CRF")
                + version.getName()
                + " "
                + respage.getString("has_been_removed_succesfully"));
        forwardPage(Page.CRF_LIST_SERVLET);
      }
    }
  }
  /*
   * (non-Javadoc)
   *
   * @see org.akaza.openclinica.control.core.SecureController#mayProceed()
   */
  @Override
  protected void mayProceed() throws InsufficientPermissionException {
    checkStudyLocked(Page.LIST_STUDY_SUBJECTS, respage.getString("current_study_locked"));
    checkStudyFrozen(Page.LIST_STUDY_SUBJECTS, respage.getString("current_study_frozen"));

    locale = request.getLocale();
    // < respage =
    // ResourceBundle.getBundle("org.akaza.openclinica.i18n.page_messages",
    // locale);
    // < restext =
    // ResourceBundle.getBundle("org.akaza.openclinica.i18n.notes",locale);
    // <
    // resexception=ResourceBundle.getBundle(
    // "org.akaza.openclinica.i18n.exceptions",locale);
    // < resword =
    // ResourceBundle.getBundle("org.akaza.openclinica.i18n.words",locale);

    getInputBeans();

    // BWP 12/2/07>> The following COUNT_VALIDATE session attribute is not
    // accessible,
    // for unknown reasons (threading problems?), when
    // double-data entry displays error messages; it's value is always 0; so
    // I have to create my
    // own session variable here to keep track of DDE stages

    // We'll go by the SectionBean's ordinal first
    int tabNumber = 1;
    if (sb != null) {
      tabNumber = sb.getOrdinal();
    }
    // if tabNumber still isn't valid, check the "tab" parameter
    if (tabNumber < 1) {
      if (fp == null) {
        fp = new FormProcessor(request);
      }
      String tab = fp.getString("tab");
      if (tab == null || tab.length() < 1) {
        tabNumber = 1;
      } else {
        tabNumber = fp.getInt("tab");
      }
    }
    SectionDAO sectionDao = new SectionDAO(sm.getDataSource());
    int crfVersionId = ecb.getCRFVersionId();
    int eventCRFId = ecb.getId();
    ArrayList sections = sectionDao.findAllByCRFVersionId(crfVersionId);
    int sectionSize = sections.size();

    HttpSession mySession = request.getSession();
    DoubleDataProgress doubleDataProgress =
        (DoubleDataProgress) mySession.getAttribute(DDE_PROGESS);
    if (doubleDataProgress == null || doubleDataProgress.getEventCRFId() != eventCRFId) {
      doubleDataProgress = new DoubleDataProgress(sectionSize, eventCRFId);
      mySession.setAttribute(DDE_PROGESS, doubleDataProgress);
    }
    boolean hasVisitedSection = doubleDataProgress.getSectionVisited(tabNumber, eventCRFId);

    // setting up one-time validation here
    // admit that it's an odd place to put it, but where else?
    // placing it in dataentryservlet is creating too many counts
    int keyId = ecb.getId();
    Integer count = (Integer) session.getAttribute(COUNT_VALIDATE + keyId);
    if (count != null) {
      count++;
      session.setAttribute(COUNT_VALIDATE + keyId, count);
      logger.info("^^^just set count to session: " + count);
    } else {
      count = 0;
      session.setAttribute(COUNT_VALIDATE + keyId, count);
      logger.info("***count not found, set to session: " + count);
    }

    DataEntryStage stage = ecb.getStage();
    if (stage.equals(DataEntryStage.INITIAL_DATA_ENTRY_COMPLETE) && !hasVisitedSection) {
      // if the user has not entered this section yet in Double Data
      // Entry, then
      // set a flag that default values should be shown in the form
      request.setAttribute(DDE_ENTERED, true);
    }
    // Now update the session attribute
    doubleDataProgress.setSectionVisited(eventCRFId, tabNumber, true);
    mySession.setAttribute("doubleDataProgress", doubleDataProgress);
    // StudyEventStatus status =
    Role r = currentRole.getRole();
    this.session.setAttribute("mayProcessUploading", "true");

    //        if (!SubmitDataServlet.maySubmitData(ub, currentRole)) {
    //            this.session.setAttribute("mayProcessUploading", "false");
    //            String exceptionName = resexception.getString("no_permission_validation");
    //            String noAccessMessage =
    // resexception.getString("not_perfom_validation_syscontact");
    //
    //            addPageMessage(noAccessMessage);
    //            throw new InsufficientPermissionException(Page.MENU, exceptionName, "1");
    //        }
    //
    //        if (stage.equals(DataEntryStage.INITIAL_DATA_ENTRY_COMPLETE)) {
    //            if (userIsOwnerAndLessThanTwelveHoursHavePassed() && !r.equals(Role.STUDYDIRECTOR)
    // && !r.equals(Role.COORDINATOR)) {
    //                this.session.setAttribute("mayProcessUploading", "false");
    //                addPageMessage(respage.getString("since_perform_data_entry"));
    //                throw new InsufficientPermissionException(Page.LIST_STUDY_SUBJECTS_SERVLET,
    // resexception.getString("owner_attempting_double_data_entry"), "1");
    //            }
    //        } else if (stage.equals(DataEntryStage.DOUBLE_DATA_ENTRY)) {
    //            if (ub.getId() != ecb.getValidatorId() && !r.equals(Role.STUDYDIRECTOR) &&
    // !r.equals(Role.COORDINATOR)) {
    //                this.session.setAttribute("mayProcessUploading", "false");
    //                addPageMessage(respage.getString("validation_has_already_begun"));
    //                throw new InsufficientPermissionException(Page.LIST_STUDY_SUBJECTS_SERVLET,
    // resexception
    //                        .getString("non_validator_attempting_double_data_entry"), "1");
    //            }
    //        } else {
    //            this.session.setAttribute("mayProcessUploading", "false");
    //            addPageMessage(respage.getString("not_perform_validation"));
    //            throw new InsufficientPermissionException(Page.LIST_STUDY_SUBJECTS_SERVLET,
    // resexception.getString("using_double_data_entry_CRF_completed"), "1");
    //        }

    return;
  }