<commit_before>package edu.duke.cabig.c3pr.web.ajax;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.extremecomponents.table.bean.Column;
import org.extremecomponents.table.bean.Row;
import org.extremecomponents.table.bean.Table;
import org.extremecomponents.table.context.Context;
import org.extremecomponents.table.context.HttpServletRequestContext;
import org.extremecomponents.table.core.TableModel;
import org.extremecomponents.table.core.TableModelImpl;

import edu.duke.cabig.c3pr.dao.StudyDao;
import edu.duke.cabig.c3pr.domain.Arm;
import edu.duke.cabig.c3pr.domain.BookRandomization;
import edu.duke.cabig.c3pr.domain.BookRandomizationEntry;
import edu.duke.cabig.c3pr.domain.Epoch;
import edu.duke.cabig.c3pr.domain.RandomizationType;
import edu.duke.cabig.c3pr.domain.StratumGroup;
import edu.duke.cabig.c3pr.utils.StringUtils;
import edu.duke.cabig.c3pr.web.study.AmendCompanionStudyController;
import edu.duke.cabig.c3pr.web.study.AmendStudyController;
import edu.duke.cabig.c3pr.web.study.CreateCompanionStudyController;
import edu.duke.cabig.c3pr.web.study.CreateStudyController;
import edu.duke.cabig.c3pr.web.study.EditCompanionStudyController;
import edu.duke.cabig.c3pr.web.study.EditStudyController;
import edu.duke.cabig.c3pr.web.study.StudyWrapper;

public class BookRandomizationAjaxFacade {

    private static Log log = LogFactory.getLog(BookRandomizationAjaxFacade.class);

    protected StudyDao studyDao;

    /*
     * This is the method that is called from the study_randomization.jsp on clicking the "Upload
     * Randomization Book" (text upload using dwr)
     */
    public String getTable(Map<String, List> parameterMap, String content, String epochIndexString,
                    HttpServletRequest req, String flowType) {
    		return getTableForWrapper(parameterMap, content, epochIndexString, req, flowType, null);
    }
    
    
    /*
     * This is the method that is called from the study_randomization for the file upload and
     * the text upload. This is also consequently called on clicking any of the table
     * buttons like pagination. As this does all the binding of uploaded data, the
     * implementation of postProcess() in StudyRandomizationTab.java contains a call to this and 
     * itself is activated in turn for file upload.
     * 
     * epochIndexString - This is the index of the epoch being dealt with. content - This is the
     * data pasted in the textarea by the user. parameterMap - this is used by the table to run its
     * own functionality like pagination.
     */
    public String getTableForWrapper(Map<String, List> parameterMap, String content,
			String epochIndexString, HttpServletRequest req, String flowType, StudyWrapper wrapper) {
		Context context;
		if (parameterMap != null) {
			context = new HttpServletRequestContext(req, parameterMap);
		} else {
			context = new HttpServletRequestContext(req);
		}

		//the wrapper is passed in in case of File upload and refData but its null in case of text upload.
		if(wrapper == null){
			wrapper = getCommandOnly(flowType, req);
		}
    	String action = getAction(flowType, wrapper);
    	
		TableModel model = new TableModelImpl(context);
		Epoch tEpoch = null;
		if (wrapper != null
				&& wrapper.getStudy().getRandomizationType() != null
				&& wrapper.getStudy().getRandomizationType().equals(
						RandomizationType.BOOK)) {
			String bookRandomizations;
			int selectedEpoch = StringUtils.getBlankIfNull(epochIndexString)
					.equals("") ? -1 : Integer.parseInt(epochIndexString);
			tEpoch = wrapper.getStudy().getEpochs().get(selectedEpoch);
			bookRandomizations = StringUtils.getBlankIfNull(content);
			if (!StringUtils.isEmpty(bookRandomizations)) {
				if (tEpoch != null) {
					try {
						if (tEpoch.getStratificationIndicator()) {
							parseBookRandomization(bookRandomizations, tEpoch);
						} else {
							parseBookRandomizationWithoutStratification(
									bookRandomizations, tEpoch);
						}
					} catch (Exception e) {
						log
								.error("Error while calling parseBookRandomization: "
										+ e.getMessage());
						return "<br/><div class='error'>Incorrect format. Please try again.</div>";
					}
					if (tEpoch.getStratificationIndicator()) {
						validatePositions(((BookRandomization) tEpoch
								.getRandomization())
								.getBookRandomizationEntry());
					} else {
						validatePositionsWithoutStratification(((BookRandomization) tEpoch
								.getRandomization())
								.getBookRandomizationEntry());
					}
				} else {
					log.error("Invalid epoch Index");
				}
			}

			if (tEpoch != null && tEpoch.getRandomization() != null) {
				List<BookRandomizationEntry> breList = ((BookRandomization) tEpoch
						.getRandomization()).getBookRandomizationEntry();
				try {
					if (tEpoch.getStratificationIndicator()) {
						return build(model, breList,
								"Book Randomization :" + selectedEpoch, action,
								flowType).toString();
					} else {
						return buildWithoutStratification(model, breList,
								"Book Randomization :" + selectedEpoch, action,
								flowType).toString();
					}
				} catch (Exception e) {
					log.error(e.getMessage());
				}
			}
		}
		return "";
	}
    
    
    private StudyWrapper getCommandOnly(String flowType, HttpServletRequest req){
    	StudyWrapper wrapper = null;
    	if (flowType.equals("CREATE_STUDY")) {
    		wrapper = (StudyWrapper) req.getSession().getAttribute(CreateStudyController.class.getName() + ".FORM.command");
    		if (wrapper == null || (wrapper != null && wrapper.getStudy().getCompanionIndicator())) {
    			wrapper = (StudyWrapper) req.getSession().getAttribute(CreateCompanionStudyController.class.getName() + ".FORM.command");
    		}
    	} else if (flowType.equals("AMEND_STUDY")) {
            wrapper = (StudyWrapper) req.getSession().getAttribute(AmendStudyController.class.getName() + ".FORM.command");
            if(wrapper == null || (wrapper != null && wrapper.getStudy().getCompanionIndicator())){
            	wrapper = (StudyWrapper) req.getSession().getAttribute(AmendCompanionStudyController.class.getName() + ".FORM.command");
            }
        } else {
            wrapper = (StudyWrapper) req.getSession().getAttribute(EditStudyController.class.getName() + ".FORM.command");
            if(wrapper == null || (wrapper != null && wrapper.getStudy().getCompanionIndicator())){
            	wrapper = (StudyWrapper) req.getSession().getAttribute(EditCompanionStudyController.class.getName() + ".FORM.command");
            }
        }
    	return wrapper;
    }
    
    private String getAction(String flowType, StudyWrapper wrapper){
    	String action ="";
    	if (flowType.equals("CREATE_STUDY")) {
            action = "/pages/study/createStudy";
    		if (wrapper == null || (wrapper != null && wrapper.getStudy().getCompanionIndicator())) {
    			action = "/pages/study/createCompanionStudy";
    		}
    	} else if (flowType.equals("AMEND_STUDY")) {
            action = "/pages/study/amendStudy";
            if(wrapper == null || (wrapper != null && wrapper.getStudy().getCompanionIndicator())){
            	action = "/pages/study/amendCompanionStudy";
            }
        } else {
            action = "/pages/study/editStudy";
            if(wrapper == null || (wrapper != null && wrapper.getStudy().getCompanionIndicator())){
            	action = "/pages/study/editCompanionStudy";
            }
        }
    	return action;
    }

    /*
	 * This method goes through the positions and ensures that they start with 0
	 * and increment by 1 for every stratum group number. if any incorrect
	 * number is found it is replaced by null. the buildTable replaces blank
	 * string with "Invalid Entry".
	 */
    private void validatePositions(List<BookRandomizationEntry> breList) {
        Iterator iter = breList.iterator();
        BookRandomizationEntry bre;
        int i = 0;
        int strGroupNumber = 0;
        while (iter.hasNext()) {
            bre = (BookRandomizationEntry) iter.next();
            if (bre.getStratumGroup() != null
                            && bre.getStratumGroup().getStratumGroupNumber() != null
                            && bre.getStratumGroup().getStratumGroupNumber().intValue() != strGroupNumber) {
                i = 0;
            }
            strGroupNumber = bre.getStratumGroup().getStratumGroupNumber().intValue();
            if (bre.getPosition() != null && bre.getPosition().intValue() != i) {
                bre.setPosition(null);
            }
            ++i;
        }
    }
    
    /*<commit_msg>Updated the study flow to use the constants for getCommandOnly method of BookRandomization<commit_after>package edu.duke.cabig.c3pr.web.ajax;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.extremecomponents.table.bean.Column;
import org.extremecomponents.table.bean.Row;
import org.extremecomponents.table.bean.Table;
import org.extremecomponents.table.context.Context;
import org.extremecomponents.table.context.HttpServletRequestContext;
import org.extremecomponents.table.core.TableModel;
import org.extremecomponents.table.core.TableModelImpl;

import edu.duke.cabig.c3pr.dao.StudyDao;
import edu.duke.cabig.c3pr.domain.Arm;
import edu.duke.cabig.c3pr.domain.BookRandomization;
import edu.duke.cabig.c3pr.domain.BookRandomizationEntry;
import edu.duke.cabig.c3pr.domain.Epoch;
import edu.duke.cabig.c3pr.domain.RandomizationType;
import edu.duke.cabig.c3pr.domain.StratumGroup;
import edu.duke.cabig.c3pr.utils.StringUtils;
import edu.duke.cabig.c3pr.web.study.AmendCompanionStudyController;
import edu.duke.cabig.c3pr.web.study.AmendStudyController;
import edu.duke.cabig.c3pr.web.study.CreateCompanionStudyController;
import edu.duke.cabig.c3pr.web.study.CreateStudyController;
import edu.duke.cabig.c3pr.web.study.EditCompanionStudyController;
import edu.duke.cabig.c3pr.web.study.EditStudyController;
import edu.duke.cabig.c3pr.web.study.StudyController;
import edu.duke.cabig.c3pr.web.study.StudyWrapper;

public class BookRandomizationAjaxFacade {

    private static Log log = LogFactory.getLog(BookRandomizationAjaxFacade.class);

    protected StudyDao studyDao;

    /*
     * This is the method that is called from the study_randomization.jsp on clicking the "Upload
     * Randomization Book" (text upload using dwr)
     */
    public String getTable(Map<String, List> parameterMap, String content, String epochIndexString,
                    HttpServletRequest req, String flowType) {
    		return getTableForWrapper(parameterMap, content, epochIndexString, req, flowType, null);
    }
    
    
    /*
     * This is the method that is called from the study_randomization for the file upload and
     * the text upload. This is also consequently called on clicking any of the table
     * buttons like pagination. As this does all the binding of uploaded data, the
     * implementation of postProcess() in StudyRandomizationTab.java contains a call to this and 
     * itself is activated in turn for file upload.
     * 
     * epochIndexString - This is the index of the epoch being dealt with. content - This is the
     * data pasted in the textarea by the user. parameterMap - this is used by the table to run its
     * own functionality like pagination.
     */
    public String getTableForWrapper(Map<String, List> parameterMap, String content,
			String epochIndexString, HttpServletRequest req, String flowType, StudyWrapper wrapper) {
		Context context;
		if (parameterMap != null) {
			context = new HttpServletRequestContext(req, parameterMap);
		} else {
			context = new HttpServletRequestContext(req);
		}

		//the wrapper is passed in in case of File upload and refData but its null in case of text upload.
		if(wrapper == null){
			wrapper = getCommandOnly(flowType, req);
		}
    	String action = getAction(flowType, wrapper);
    	
		TableModel model = new TableModelImpl(context);
		Epoch tEpoch = null;
		if (wrapper != null
				&& wrapper.getStudy().getRandomizationType() != null
				&& wrapper.getStudy().getRandomizationType().equals(
						RandomizationType.BOOK)) {
			String bookRandomizations;
			int selectedEpoch = StringUtils.getBlankIfNull(epochIndexString)
					.equals("") ? -1 : Integer.parseInt(epochIndexString);
			tEpoch = wrapper.getStudy().getEpochs().get(selectedEpoch);
			bookRandomizations = StringUtils.getBlankIfNull(content);
			if (!StringUtils.isEmpty(bookRandomizations)) {
				if (tEpoch != null) {
					try {
						if (tEpoch.getStratificationIndicator()) {
							parseBookRandomization(bookRandomizations, tEpoch);
						} else {
							parseBookRandomizationWithoutStratification(
									bookRandomizations, tEpoch);
						}
					} catch (Exception e) {
						log
								.error("Error while calling parseBookRandomization: "
										+ e.getMessage());
						return "<br/><div class='error'>Incorrect format. Please try again.</div>";
					}
					if (tEpoch.getStratificationIndicator()) {
						validatePositions(((BookRandomization) tEpoch
								.getRandomization())
								.getBookRandomizationEntry());
					} else {
						validatePositionsWithoutStratification(((BookRandomization) tEpoch
								.getRandomization())
								.getBookRandomizationEntry());
					}
				} else {
					log.error("Invalid epoch Index");
				}
			}

			if (tEpoch != null && tEpoch.getRandomization() != null) {
				List<BookRandomizationEntry> breList = ((BookRandomization) tEpoch
						.getRandomization()).getBookRandomizationEntry();
				try {
					if (tEpoch.getStratificationIndicator()) {
						return build(model, breList,
								"Book Randomization :" + selectedEpoch, action,
								flowType).toString();
					} else {
						return buildWithoutStratification(model, breList,
								"Book Randomization :" + selectedEpoch, action,
								flowType).toString();
					}
				} catch (Exception e) {
					log.error(e.getMessage());
				}
			}
		}
		return "";
	}
    
    
    private StudyWrapper getCommandOnly(String flowType, HttpServletRequest req){
    	StudyWrapper wrapper = null;
    	if (flowType.equals(StudyController.CREATE_STUDY)) {
    		return (StudyWrapper) req.getSession().getAttribute(CreateStudyController.class.getName() + ".FORM.command");
    	}
    	if (flowType.equals(StudyController.CREATE_COMPANION_STUDY)) {
    		return (StudyWrapper) req.getSession().getAttribute(CreateCompanionStudyController.class.getName() + ".FORM.command");
		}
    	if (flowType.equals(StudyController.AMEND_STUDY)) {
    		return (StudyWrapper) req.getSession().getAttribute(AmendStudyController.class.getName() + ".FORM.command");
        } 
    	if(flowType.equals(StudyController.AMEND_COMPANION_STUDY)){
    		return (StudyWrapper) req.getSession().getAttribute(AmendCompanionStudyController.class.getName() + ".FORM.command");
        }
    	if(flowType.equals(StudyController.EDIT_STUDY)){
    		return (StudyWrapper) req.getSession().getAttribute(EditStudyController.class.getName() + ".FORM.command");
        }
    	if(flowType.equals(StudyController.EDIT_COMPANION_STUDY)){
    		return (StudyWrapper) req.getSession().getAttribute(EditCompanionStudyController.class.getName() + ".FORM.command");
        }
    	return wrapper;
    }
    
    
    private String getAction(String flowType, StudyWrapper wrapper){
    	String action ="";
    	if (flowType.equals(StudyController.CREATE_STUDY)) {
    		return "/pages/study/createStudy";
    	}
    	if (flowType.equals(StudyController.CREATE_COMPANION_STUDY)) {
    		return "/pages/study/createCompanionStudy";
		}
    	if (flowType.equals(StudyController.AMEND_STUDY)) {
    		return "/pages/study/amendStudy";
        } 
    	if(flowType.equals(StudyController.AMEND_COMPANION_STUDY)){
    		return "/pages/study/amendCompanionStudy";
        }
    	if(flowType.equals(StudyController.EDIT_STUDY)){
    		return "/pages/study/editStudy";
        }
    	if(flowType.equals(StudyController.EDIT_COMPANION_STUDY)){
    		return "/pages/study/editCompanionStudy";
        }
    	return action;
    }

    /*
	 * This method goes through the positions and ensures that they start with 0
	 * and increment by 1 for every stratum group number. if any incorrect
	 * number is found it is replaced by null. the buildTable replaces blank
	 * string with "Invalid Entry".
	 */
    private void validatePositions(List<BookRandomizationEntry> breList) {
        Iterator iter = breList.iterator();
        BookRandomizationEntry bre;
        int i = 0;
        int strGroupNumber = 0;
        while (iter.hasNext()) {
            bre = (BookRandomizationEntry) iter.next();
            if (bre.getStratumGroup() != null
                            && bre.getStratumGroup().getStratumGroupNumber() != null
                            && bre.getStratumGroup().getStratumGroupNumber().intValue() != strGroupNumber) {
                i = 0;
            }
            strGroupNumber = bre.getStratumGroup().getStratumGroupNumber().intValue();
            if (bre.getPosition() != null && bre.getPosition().intValue() != i) {
                bre.setPosition(null);
            }
            ++i;
        }
    }
    
    /*
{'fraction_non_alphanumeric': 0.1082755484824372, 'fraction_numerical': 0.002557690121632375, 'mean_word_length': 3.2998533724340176, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3114798', 'n_tokens_mistral': 5812, 'n_tokens_neox': 5155, 'n_words': 1096}