/***********************************************************************************
 * @@ Program Name : StaticMReportViewer.java Description : 보고한 보고자료와 문서 양식을 조합하여 보고자료 보기 처리 해줌 Author : 강원중 Create Date
 *    : 2004-10-21 History :
 * @@
 ***********************************************************************************/
package kr.co.kihyun.beans.totsys.report;

import kr.co.kihyun.beans.entity.TotDoc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import kr.co.kihyun.beans.totsys.doc.Doc;
import kr.co.kihyun.lang.MString;
import kr.co.kihyun.moumi.doc.table.InsertMTable;
import kr.co.kihyun.moumi.doc.table.item.MItem;
import kr.co.kihyun.moumi.report.dyna.DynaMReport;
import kr.co.kihyun.text.html.HtmlUtil;

public class ReportRegistFormElement extends ReportFormElement {

	private static final Logger LOG = LoggerFactory.getLogger(ReportRegistFormElement.class);
	private int rowCount;
	private String inForm;
	private String inTitleForm;
	private String inBodyForm;
	private String inTailForm;
	private String[] inTitleForms;
	private String[] inBodyForms;
	private String[] inTailForms;
	private StringBuilder inFormBuf;
	private String putValScript;
	private String changeAllScript;
	private int size = 0;
	private String[] tableRowList;
	private int[] tableColNumList;
	private int edItemNum = 0;
	private String[] stItemNameList = null;
	private String[] stItemNumList = null;

	protected ReportRegistFormElement(TotDoc totDoc, int rowCount) {
		super(totDoc);
		this.rowCount = rowCount;
		setForm(totDoc, rowCount);
	}

	protected ReportRegistFormElement(TotDoc totDoc, int rowCount, String tableRows) {
		super(totDoc);
		this.rowCount = rowCount;
		setForm(totDoc, rowCount, tableRows);
        
        
	}

	protected final void setForm(TotDoc totDoc, int rowCount) {
		itemAnalysis(totDoc);

		/*********** 입력 폼 생성 ***********/
		InsertMTable inMTable = new InsertMTable();

		inMTable.convert(getForm(), super.getItemList(), getDefItemSize());
		setInForm(inMTable.getInputForm()); // 입력에 최적화 되어 있음

		setInTitleForm(inMTable.getInputTitleForm(getInForm()));
		setInBodyForm(inMTable.getInputBodyForm(getInForm()));
		setInBodyForm(DynaMReport.addRow(getInBodyForm(), rowCount));
		setInTailForm(HtmlUtil.getTailForm(getInForm()));

		setInFormBuf(new StringBuilder(1024));
		getInFormBuf().append(MString.checkNull(getInTitleForm()));
		getInFormBuf().append(getInBodyForm());
		getInFormBuf().append(getInTailForm());
		/*********** insert form: item Analysis values ***********/
		setStItemNameList(MItem.getStartNameList(getInForm(), getInItemCount()));
		setEdItemNum(MItem.getEndNum(getInForm()));

		setInItemNameList(MItem.getInNameList(getStItemNameList(), getEdItemNum(), rowCount, getInItemCount()));

		/*********** insert form: java script create ***********/

		setPutValScript(inMTable.getPutValScript());
		setChangeAllScript(inMTable.getChangeAllScript());



		if (rowCount > 1) { // 동적표에서만 가능
			setChangeAllScript(inMTable.getChangeAllScript(getChangeAllScript(), getEdItemNum(), rowCount));
		}
		setChangeAllScript(getChangeAllScript().replaceAll("[$]", "."));

	}

	protected final void setForm(TotDoc totDoc, int rowCount, String tableRows) {
		itemAnalysis(totDoc);

		/*********** 입력 폼 생성 ***********/
		InsertMTable inMTable = new InsertMTable();


		inMTable.convert(getForm(), super.getItemList(), getDefItemSize());

		setInForm(inMTable.getInputForm()); // 입력에 최적화 되어 있음

		/****************** 새로 수정 소스 *****************/
		Doc doc = new Doc();
		setTableTypes(doc.getTableTypes(totDoc.getId()));

		String[] tableTypeList = getTableTypes().split(",");
		String[] tableRowList;
		if (tableRows != null && tableRows.length() != 0) {
			tableRowList = tableRows.split(",");
		} else {
			tableRowList = new String[tableTypeList.length];
			for (int i = 0; i < tableTypeList.length; i++) {
				tableRowList[i] = "1";
			}
		}
		int[] tableColNumList = new int[tableTypeList.length]; // 원본 폼의 각 테이블당 몇개의 입력칸이 존재 하는지 그 수 저장


		setInTitleForms(new String[tableTypeList.length]);
		setInBodyForms(new String[tableTypeList.length]);
		setInTailForms(new String[tableTypeList.length]);

		String subForm = null;
		int subFpos = 0;
		setInForm(getInForm().replaceAll("<TABLE", "<table"));
		setInForm(getInForm().replaceAll("</TABLE", "</table"));

//24.Public 메소드로부터 반환된 Private배열_CWE-495 : Update by KWON,HAN      
/*
		for (int i = 0; i < tableTypeList.length; i++) {
			subForm = getInForm().substring(subFpos, getInForm().indexOf("</table>", subFpos) + 8);
			subFpos = getInForm().indexOf("</table>", subFpos) + 8;

			if (tableTypeList[i].equals("1")) {

	                        getInTitleForms()[i] = inMTable.getInputTitleForm(subForm);

				getInBodyForms()[i] = inMTable.getInputBodyForm(subForm);                            
                                
				// 몇개의 입력칸이 존재하는지 숫자 파악
				try {
					tableColNumList[i] = 0;
					if (getInBodyForms()[i].indexOf("<input type") != -1) {
						tableColNumList[i] = getInBodyForms()[i].split("<input type").length - 1;
					}
					if (getInBodyForms()[i].indexOf("<textarea ") != -1) {
						tableColNumList[i] = tableColNumList[i] + getInBodyForms()[i].split("<textarea ").length - 1;
					}
					if (getInBodyForms()[i].indexOf("<select ") != -1) {
						tableColNumList[i] = tableColNumList[i] + getInBodyForms()[i].split("<select ").length - 1;
					}
					getInBodyForms()[i] = DynaMReport.addRow(getInBodyForms()[i], Integer.parseInt(tableRowList[i]));
				} catch (NullPointerException npe) {
					throw new NullPointerException("inBodyForms[" + i + "] is null. subForm: " + subForm);
				}
			} else {
				getInTitleForms()[i] = "";
				getInBodyForms()[i] = subForm.substring(0, subForm.indexOf("</table"));
				// 몇개의 입력칸이 존재하는지 숫자 파악
				tableColNumList[i] = getInBodyForms()[i].split("<input type").length - 1;
				tableColNumList[i] = tableColNumList[i] + getInBodyForms()[i].split("<textarea ").length - 1;
				tableColNumList[i] = tableColNumList[i] + getInBodyForms()[i].split("<select ").length - 1;
			}
			getInTailForms()[i] = HtmlUtil.getTailForm(subForm);

			if ((i == (tableTypeList.length - 1)) && (subFpos < getInForm().length())) {
				getInTailForms()[i] = getInTailForms()[i] + getInForm().substring(subFpos);
			}
		}
		setInFormBuf(new StringBuilder(1024));
		for (int j = 0; j < tableTypeList.length; j++) {
			getInFormBuf().append(MString.checkNull(getInTitleForms()[j]));
            
			getInFormBuf().append(getInBodyForms()[j]);
            
			getInFormBuf().append(getInTailForms()[j]);
            

		}
*/
                
		for (int i = 0; i < tableTypeList.length; i++) {
			subForm = getInForm().substring(subFpos, getInForm().indexOf("</table>", subFpos) + 8);
			subFpos = getInForm().indexOf("</table>", subFpos) + 8;

			if (tableTypeList[i].equals("1")) {

	                        inTitleForms[i] = inMTable.getInputTitleForm(subForm);    //  

				inBodyForms[i] = inMTable.getInputBodyForm(subForm);    //                       
                                
				// 몇개의 입력칸이 존재하는지 숫자 파악
				try {
					tableColNumList[i] = 0;
					if (inBodyForms[i].indexOf("<input type") != -1) {    //  
						tableColNumList[i] = inBodyForms[i].split("<input type").length - 1;    //  
					}
					if (inBodyForms[i].indexOf("<textarea ") != -1) {    //  
						tableColNumList[i] = tableColNumList[i] + inBodyForms[i].split("<textarea ").length - 1;    //  
					}
					if (inBodyForms[i].indexOf("<select ") != -1) {    //  
						tableColNumList[i] = tableColNumList[i] + inBodyForms[i].split("<select ").length - 1;    //  
					}
					inBodyForms[i] = DynaMReport.addRow(inBodyForms[i], Integer.parseInt(tableRowList[i]));    //  
				} catch (NullPointerException npe) {
					throw new NullPointerException("inBodyForms[" + i + "] is null. subForm: " + subForm);
				}
			} else {
				inTitleForms[i] = "";    //  
				inBodyForms[i] = subForm.substring(0, subForm.indexOf("</table"));    //  
				// 몇개의 입력칸이 존재하는지 숫자 파악
				tableColNumList[i] = inBodyForms[i].split("<input type").length - 1;    //  
                                
                                //v2 22.정수형 오버플로우_CWE-190 : Update by YOUNGJUN,CHO
                                if ((tableColNumList[i] + inBodyForms[i].split("<textarea ").length - 1) < Integer.MAX_VALUE) {
                                    tableColNumList[i] = tableColNumList[i] + inBodyForms[i].split("<textarea ").length - 1;
                                } else {
                                    throw new RuntimeException("ReportRegistFormElement setForm() 22.정수형 오버플로우_CWE-190");
                                }
				
                                if ((tableColNumList[i] + inBodyForms[i].split("<select ").length - 1) < Integer.MAX_VALUE) {
                                    tableColNumList[i] = tableColNumList[i] + inBodyForms[i].split("<select ").length - 1;
                                } else {
                                    throw new RuntimeException("ReportRegistFormElement setForm() 22.정수형 오버플로우_CWE-190");
                                }
				//================================================
                                
			}
			inTailForms[i] = HtmlUtil.getTailForm(subForm);    //  

			if ((i == (tableTypeList.length - 1)) && (subFpos < getInForm().length())) {
				inTailForms[i] = inTailForms[i] + getInForm().substring(subFpos);    //  
			}
		}
		setInFormBuf(new StringBuilder(1024));
		for (int j = 0; j < tableTypeList.length; j++) {
			getInFormBuf().append(MString.checkNull(inTitleForms[j]));
            
			getInFormBuf().append(inBodyForms[j]);    //  
            
			getInFormBuf().append(inTailForms[j]);    //  
            

		}
                
//==============================================================================
                

		//LOG.debug("inFormBuf: {}", getInFormBuf());
		/***************** 새로 수정 소스 끝 ***************/
		/*********** insert form: item Analysis values ***********/
		setStItemNameList(MItem.getStartNameList(getInForm(), getInItemCount()));
		setStItemNumList(MItem.getStartNumList(getInForm(), getInItemCount()));
		setEdItemNum(MItem.getEndNum(getInForm()));
		String[] tmpstNameList = new String[getStItemNameList().length];
		String[] tmpstNumList = new String[getStItemNumList().length];
		System.arraycopy(getStItemNameList(), 0, tmpstNameList, 0, getStItemNameList().length);
		System.arraycopy(getStItemNumList(), 0, tmpstNumList, 0, getStItemNumList().length);

		this.setTableColNumList(tableColNumList);
		this.setTableRowList(tableRowList);
		setInItemNameList(MItem.getInNameList(tmpstNameList, tmpstNumList, tableColNumList, tableRowList));
		setSize(0);
		for (int i = 0; i < tableColNumList.length; i++) {
			setSize(getSize() + tableColNumList[i] * Integer.parseInt(tableRowList[i]));
		}
		/*********** insert form: java script create ***********/
		setPutValScript(inMTable.getPutValScript());
		setChangeAllScript(inMTable.getChangeAllScript());
		// if(rowCount > 1){ //동적표에서만 가능
		if (getTableTypes().indexOf("1") != -1) {
			System.arraycopy(getStItemNameList(), 0, tmpstNameList, 0, getStItemNameList().length);
			System.arraycopy(getStItemNumList(), 0, tmpstNumList, 0, getStItemNumList().length);
			setInFormBuf(nameSet(getInFormBuf().toString(), getInItemNameList()));
			setInFormBuf(dateSet(getInFormBuf().toString()));
			System.arraycopy(getStItemNameList(), 0, tmpstNameList, 0, getStItemNameList().length);
			System.arraycopy(getStItemNumList(), 0, tmpstNumList, 0, getStItemNumList().length);
			setChangeAllScript(inMTable.getChangeAllScript(getChangeAllScript(), tmpstNameList, tmpstNumList, tableColNumList, tableRowList));

		}
		setChangeAllScript(getChangeAllScript().replaceAll("[$]", "."));
	}

	public StringBuilder nameSet(String inForm, String[] inItemNameList) {
		StringBuilder newForm = new StringBuilder(1024);

		String inputTag = "<input type='text' name='";
		String selectTag = "<select name='";
		String textAreaTag = "<textarea name='";

		int inputLength = inputTag.length();
		int selectLength = selectTag.length();
		int textAreaLength = textAreaTag.length();

		int here = 0;
		for (int i = 0; i < inItemNameList.length; i++) {
			int minS = 0;
			int min = 0;
			int in = inForm.indexOf(inputTag, here);
			int sn = inForm.indexOf(selectTag, here);
			int tn = inForm.indexOf(textAreaTag, here);

			/*** -1이 아닌 가장 작은 수 구하기 ***/
			if (in <= sn && in <= tn) {
				if (in > -1) {
					min = in;
					minS = 1;
				} else if ((sn <= tn && sn > -1) || tn == -1) {
					min = sn;
					minS = 2;
				} else {
					min = tn;
					minS = 3;
				}
			} else if (sn <= tn) {
				if (sn > -1) {
					min = sn;
					minS = 2;
				} else if ((in <= tn && in > -1) || tn == -1) {
					min = in;
					minS = 1;
				} else {
					min = tn;
					minS = 3;
				}
			} else {
				if (tn > -1) {
					min = tn;
					minS = 3;
				} else if ((sn <= in && sn > -1) || in == -1) {
					min = sn;
					minS = 2;
				} else {
					min = in;
					minS = 1;
				}
			}
                        
                        //42.비어있는 if문 : Update by YOUNGJUN,CHO
			//if (min == -1) {
			//} else if (minS == 1) {
                        
                        if (minS == 1) {
				newForm.append(inForm.substring(here, in + inputLength));
				newForm.append(inItemNameList[i]);
				here = inForm.indexOf("'", in + inputLength);
			} else if (minS == 2) {
				newForm.append(inForm.substring(here, sn + selectLength));
				newForm.append(inItemNameList[i]);
				here = inForm.indexOf("'", sn + selectLength);
			} else if (minS == 3) {
				newForm.append(inForm.substring(here, tn + textAreaLength));
				newForm.append(inItemNameList[i]);
				here = inForm.indexOf("'", tn + textAreaLength);
			}
                        //================================================
		}
		newForm.append(inForm.substring(here));

		return newForm;
	}

	public StringBuilder dateSet(String inForm) {
		StringBuilder newForm = new StringBuilder(1024);

		String setWin = "showSetWin('";
		String inTag = "<input type='text' name='";

		int swLength = setWin.length();
		int inLength = inTag.length();

		int here = 0;
		for (here = inForm.indexOf(setWin, here); here != -1; here = inForm.indexOf(setWin, here)) {
			here = here + swLength;

			int iptS = inForm.indexOf(inTag, here) + inLength;
			int iptE = inForm.indexOf("'", iptS);
			String iptName = inForm.substring(iptS, iptE);

			inForm = inForm.substring(0, here) + "dform." + iptName + inForm.substring(inForm.indexOf("'", here));
			here = inForm.indexOf(setWin, here);
			if (here == -1) {
				break;
			}
			here = here + swLength;
			inForm = inForm.substring(0, here) + "dform." + iptName + inForm.substring(inForm.indexOf("'", here));
		}
		return newForm.append(inForm);
	}

	public String getBaseInsertForm() {
		return getInForm();
	}

	public String getPutValScript() {
		return putValScript;
	}

	public String getChangeAllScript() {
		return changeAllScript;
	}

	public int getEndItemNum() {
		return getEdItemNum();
	}

	public String[] getStartItemNameList() {
		return getStItemNameList();
	}

	/**
	 * @return the rowCount
	 */
	public int getRowCount() {
		return rowCount;
	}

	/**
	 * @param rowCount the rowCount to set
	 */
	public void setRowCount(int rowCount) {
		this.rowCount = rowCount;
	}

	/**
	 * @return the inForm
	 */
	public String getInForm() {
		return inForm;
	}

	/**
	 * @param inForm the inForm to set
	 */
	public void setInForm(String inForm) {
		this.inForm = inForm;
	}

	/**
	 * @return the inTitleForm
	 */
	public String getInTitleForm() {
		return inTitleForm;
	}

	/**
	 * @param inTitleForm the inTitleForm to set
	 */
	public void setInTitleForm(String inTitleForm) {
		this.inTitleForm = inTitleForm;
	}

	/**
	 * @return the inBodyForm
	 */
	public String getInBodyForm() {
		return inBodyForm;
	}

	/**
	 * @param inBodyForm the inBodyForm to set
	 */
	public void setInBodyForm(String inBodyForm) {
		this.inBodyForm = inBodyForm;
	}

	/**
	 * @return the inTailForm
	 */
	public String getInTailForm() {
		return inTailForm;
	}

	/**
	 * @param inTailForm the inTailForm to set
	 */
	public void setInTailForm(String inTailForm) {
		this.inTailForm = inTailForm;
	}

	/**
	 * @return the inTitleForms
	 */
	public String[] getInTitleForms() {
            //24.Public 메소드로부터 반환된 Private배열_CWE-495 : Update by KWON,HAN
	    //	return inTitleForms;
                
            String[] ret = null;
            if( this.inTitleForms != null) {
                ret = new String[inTitleForms.length];
                for (int i=0; i<inTitleForms.length; i++) {
                    ret[i] = this.inTitleForms[i];
                }
            }
            return ret;
            //====================================================================                    
	}

	/**
	 * @param inTitleForms the inTitleForms to set
	 */
	public void setInTitleForms(String[] inTitleForms) {
            //01.Private 배열에 Public 데이터 할당_CWE-496 : Update by KWON,HAN
		//this.inTitleForms = inTitleForms;
            
            this.inTitleForms = new String[inTitleForms.length];
            for(int i = 0; i < inTitleForms.length; ++i) {
                this.inTitleForms[i] = inTitleForms[i];            
            }
            //===============================================================  
	}

	/**
	 * @return the inBodyForms
	 */
	public String[] getInBodyForms() {
	    //	return inBodyForms;
                
            String[] ret = null;
            if( this.inBodyForms != null) {
                
                //v2 23.정수형 오버플로우 (배열인덱스)_CWE-190 : Update by YOUNGJUN,CHO
                if (inBodyForms.length > 0) {
                    ret = new String[inBodyForms.length];
                    for (int i=0; i<inBodyForms.length; i++) {
                        ret[i] = this.inBodyForms[i];
                    }
                }
                //================================================
            }
            return ret;                
	}

	/**
	 * @param inBodyForms the inBodyForms to set
	 */
	public void setInBodyForms(String[] inBodyForms) {
	    //	this.inBodyForms = inBodyForms;
                
            this.inBodyForms = new String[inBodyForms.length];
            for(int i = 0; i < inBodyForms.length; ++i) {
                this.inBodyForms[i] = inBodyForms[i];            
            }
	}

	/**
	 * @return the inTailForms
	 */
	public String[] getInTailForms() {
	    //	return inTailForms;
                
            String[] ret = null;
            if( this.inTailForms != null) {
                ret = new String[inTailForms.length];
                for (int i=0; i<inTailForms.length; i++) {
                    ret[i] = this.inTailForms[i];
                }
            }
            return ret;                 
	}

	/**
	 * @param inTailForms the inTailForms to set
	 */
	public void setInTailForms(String[] inTailForms) {
	    //	this.inTailForms = inTailForms;
                
            this.inTailForms = new String[inTailForms.length];
            for(int i = 0; i < inTailForms.length; ++i) {
                this.inTailForms[i] = inTailForms[i];            
            }
	}

	/**
	 * @return the inFormBuf
	 */
	public StringBuilder getInFormBuf() {
		return inFormBuf;
	}

	/**
	 * @param inFormBuf the inFormBuf to set
	 */
	public void setInFormBuf(StringBuilder inFormBuf) {
		this.inFormBuf = inFormBuf;
	}

	/**
	 * @param putValScript the putValScript to set
	 */
	public void setPutValScript(String putValScript) {
		this.putValScript = putValScript;
	}

	/**
	 * @param changeAllScript the changeAllScript to set
	 */
	public void setChangeAllScript(String changeAllScript) {
		this.changeAllScript = changeAllScript;
	}

	/**
	 * @return the size
	 */
	public int getSize() {
		return size;
	}

	/**
	 * @param size the size to set
	 */
	public void setSize(int size) {
		this.size = size;
	}

	/**
	 * @return the tableRowList
	 */
	public String[] getTableRowList() {
	    //	return tableRowList;
                
            String[] ret = null;
            if( this.tableRowList != null) {
                ret = new String[tableRowList.length];
                for (int i=0; i<tableRowList.length; i++) {
                    ret[i] = this.tableRowList[i];
                }
            }
            return ret;                
	}

	/**
	 * @param tableRowList the tableRowList to set
	 */
	public void setTableRowList(String[] tableRowList) {
	    //	this.tableRowList = tableRowList;
                
            this.tableRowList = new String[tableRowList.length];
            for(int i = 0; i < tableRowList.length; ++i) {
                this.tableRowList[i] = tableRowList[i];            
            }
	}

	/**
	 * @return the tableColNumList
	 */
	public int[] getTableColNumList() {
	    //	return tableColNumList;
                
            int[] ret = null;
            if( this.tableColNumList != null) {
                ret = new int[tableColNumList.length];
                for (int i=0; i<tableColNumList.length; i++) {
                    ret[i] = this.tableColNumList[i];
                }
            }
            return ret;                 
	}

	/**
	 * @param tableColNumList the tableColNumList to set
	 */
	public void setTableColNumList(int[] tableColNumList) {
	    //	this.tableColNumList = tableColNumList;
                
            this.tableColNumList = new int[tableColNumList.length];
            for(int i = 0; i < tableColNumList.length; ++i) {
                this.tableColNumList[i] = tableColNumList[i];            
            }                
	}

	/**
	 * @return the edItemNum
	 */
	public int getEdItemNum() {
		return edItemNum;
	}

	/**
	 * @param edItemNum the edItemNum to set
	 */
	public void setEdItemNum(int edItemNum) {
		this.edItemNum = edItemNum;
	}

	/**
	 * @return the stItemNameList
	 */
	public String[] getStItemNameList() {
	    //	return stItemNameList;
                
            String[] ret = null;
            if( this.stItemNameList != null) {
                ret = new String[stItemNameList.length];
                for (int i=0; i<stItemNameList.length; i++) {
                    ret[i] = this.stItemNameList[i];
                }
            }
            return ret;                
	}

	/**
	 * @param stItemNameList the stItemNameList to set
	 */
	public void setStItemNameList(String[] stItemNameList) {
	    //	this.stItemNameList = stItemNameList;
                
            this.stItemNameList = new String[stItemNameList.length];
            for(int i = 0; i < stItemNameList.length; ++i) {
                this.stItemNameList[i] = stItemNameList[i];            
            }                
	}

	/**
	 * @return the stItemNumList
	 */
	public String[] getStItemNumList() {
	    //	return stItemNumList;
                
            String[] ret = null;
            if( this.stItemNumList != null) {
                ret = new String[stItemNumList.length];
                for (int i=0; i<stItemNumList.length; i++) {
                    ret[i] = this.stItemNumList[i];
                }
            }
            return ret;                
	}

	/**
	 * @param stItemNumList the stItemNumList to set
	 */
	public void setStItemNumList(String[] stItemNumList) {
	    //	this.stItemNumList = stItemNumList;
                
            this.stItemNumList = new String[stItemNumList.length];
            for(int i = 0; i < stItemNumList.length; ++i) {
                this.stItemNumList[i] = stItemNumList[i];            
            }                
	}
}
