/*********************************************************************************************************
 * 프로그램명 : DynaReportUtil.java 프로그램설명 : 프로젝트와 관련된 정보를 얻을수 있는 class 작성자 : 강원중 작성일 : 2003.11.30 변경일 : 2003.12.13
 **********************************************************************************************************/

package kr.co.kihyun.moumi.report.dyna;

import java.util.*;
import java.text.*;

import kr.co.kihyun.moumi.Moumi;
import kr.co.kihyun.text.html.Html;
import kr.co.kihyun.moumi.report.MReport;
import kr.co.kihyun.moumi.doc.table.item.MItem;

public class DynaMReport extends MReport {

	public String getReportInsertWidth(String form) {
		String result = null;
		result = form;
		int stTABLE = 0;
		int stWidth = 0;
		String edResult = "";
		StringBuffer insertData = new StringBuffer();
		stTABLE = result.indexOf("<table", stTABLE);
		while (true) {

			if (stTABLE == -1)
				break;
			stWidth = result.indexOf("width=", stTABLE);
			if (stWidth == -1)
				break;
			edResult = edResult + result.substring(stTABLE, stWidth + 6);
			edResult = edResult + "100% " + Html.width + "=";
			edResult = edResult + result.substring(stWidth + 6, result.length());
			stTABLE = result.indexOf("<table", stTABLE + 6);
		}

		if (stWidth == -1) {
			edResult = result;
			edResult = "";
			stTABLE = 0;
			while (true) {
				stTABLE = result.indexOf("<table");
				if (stTABLE == -1)
					break;
				insertData.append(result.substring(0, stTABLE + 6));
				insertData.append(" width=100% ");
				result = result.substring(stTABLE + 6, result.length());
			}
			insertData.append(result);
			edResult = insertData.toString();
		}

		return edResult.replaceAll("style", "ss");
	}

	/******************* Dynamic Report util *******************/
	public String getAddLineData(String titleTable, String inDatas, int[] itemType, String printType) throws Exception {
		if (titleTable == null)
			return null;
		return getAddLineData(new StringBuffer(titleTable), inDatas, itemType, printType);
	}

	public String getAddLineData(StringBuffer titleTable, String inDatas, int[] itemType, String printType)
			throws Exception {

		String inData = "";
		StringBuffer inDataBuf = new StringBuffer();

		inDatas = inDatas.replace('{', ' ').replaceAll(", ", " ");

		StringTokenizer st1 = null; // record data
		StringTokenizer st2 = null; // field data (각각의 item data)

		st1 = new StringTokenizer(inDatas, "}");
		double dValue;
		String sValue;
		for (int i = 0, j = 0; st1.hasMoreTokens(); i++) {
			inDatas = st1.nextToken();
			inDataBuf.append("<tr>");
			if (inDatas.indexOf("&#") == -1) {
				st2 = new StringTokenizer(inDatas.trim(), ",");
			} else {
				st2 = new StringTokenizer(inDatas.trim(), "&#");
			}

			int index = itemType.length - st2.countTokens();

			for (j = 0; st2.hasMoreTokens(); j++) {
				inData = st2.nextToken();
				if (inData.equals("empty")) {
					inData = "&nbsp;";
				}
				if (itemType[j + index] == MItem.INT) {// 숫자이면
					inDataBuf.append("<td align=right>");
					try {
						dValue = Double.parseDouble(inData);
						sValue = NumberFormat.getNumberInstance().format(dValue);
					} catch (NumberFormatException ex) {
						dValue = 0;
						sValue = Moumi.getMessageBundle().getString("moumi.message.tot_doc.outControl");
					}

					if (printType != null && printType.equals("excel")) {
						inDataBuf.append(sValue);
					} else {
						inDataBuf.append(sValue);
						inDataBuf.append("&nbsp;");
					}
				} else {
					inDataBuf.append("<td>&nbsp;");
					inDataBuf.append(inData);
				}
				inDataBuf.append("</td>");
			}

			inDataBuf.append("</tr>");
		}

		titleTable.append(inDataBuf.toString());
		return titleTable.toString();
	}

	public String getTotalLineData(String form, String allTotData, int[] itemType, String printType) {
		if (form == null)
			return null;
		return getTotalLineData(new StringBuffer(form), allTotData, itemType, printType);
	}

	public String getTotalLineData(StringBuffer form, String allTotData, int[] itemType, String printType) {

		StringBuffer insertedForm = new StringBuffer();
		String tmp = allTotData;
		StringTokenizer st = null;
		String inData = "";
		int i = 0;
		double dValue;
		String sValue;

		tmp = tmp.replace('{', ' ');
		tmp = tmp.replace('}', ' ');

		insertedForm.append("<tr>");
		if (tmp.indexOf("&#") == -1) {
			st = new StringTokenizer(tmp.trim(), ",");
		} else {
			st = new StringTokenizer(tmp.trim(), "&#");
		}

		int index = itemType.length - st.countTokens();
		while (st.hasMoreTokens()) {
			inData = st.nextToken();
			if (inData.equals("empty")) {
				inData = "&nbsp;";
			}

			if (itemType[i + index] == MItem.INT) {
				insertedForm.append("<td align=right><font color=red>");
				dValue = Double.parseDouble(inData);
				sValue = NumberFormat.getNumberInstance().format(dValue);
				if (printType != null && printType.equals("excel")) {
					insertedForm.append(sValue);
				} else {
					insertedForm.append(sValue);
					insertedForm.append("&nbsp;");
				}
			} else {
				insertedForm.append("<td><font color=red>&nbsp;");
				insertedForm.append(inData);
			}
			insertedForm.append("</font></td>");
			i++;
		}
		insertedForm.append("</tr>");

		form.append(insertedForm.toString());
		form.append("</table>");
		return form.toString();
	}

	// 동적인표에서 행추요청 처리 메소드
	public static String addRow(String inBodyForm, int rowCount) {
		StringBuffer addRowBuf = new StringBuffer();
		for (int i = 0; i < rowCount; i++) {
			addRowBuf.append(addName(i, inBodyForm));
		}
		return (addRowBuf.toString()).replaceAll("checknum", "checkNum");
	}

	// 동적인표에서 행추가요청 처리 메소드
	public static String addName(int rowNum, String inBodyForm) {

		if (inBodyForm == null)
			return inBodyForm;

		int stInput = 0;
		int stSelect = 0;
		int stTextarea = 0;
		int quoteIdx = 0;
		int serial = 0;

		String stN = "";
		String edN = "";
		String inputName = "";
		StringBuffer parserLine = new StringBuffer();
		String tmp[] = inBodyForm.split("<td");
		String tempStr = "";

		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();

		for (int i = 0; i < tmp.length; i++) {
			stInput = tmp[i].indexOf(inputTag);// 입력창
			stSelect = tmp[i].indexOf(selectTag);// 콤보
			stTextarea = tmp[i].indexOf(textAreaTag);// textarea

			if (stInput >= 0) {
				quoteIdx = tmp[i].indexOf("'", stInput + inputLength);
				if (quoteIdx == -1)
					break;

				stN = tmp[i].substring(stInput + inputLength, quoteIdx).replaceAll("[0-9]", "");
				stN = stN.trim(); // A~Z

				edN = tmp[i].substring(stInput + inputLength, quoteIdx).replaceAll("[a-zA-Z]", "");
				serial = Integer.parseInt(edN.trim()) + rowNum; // 숫자

				if (i == 0) {
					parserLine = parserLine.append(tmp[i].substring(0, stInput + inputLength));
				} else {
					parserLine.append("<td");
					parserLine.append(tmp[i].substring(0, stInput + inputLength));
				}
                                
                                //v2 22.정수형 오버플로우_CWE-190 : Comment by YOUNGJUN,CHO
                                // 문자열을 합치는 부분으로 정수형 오버플로우와는 상관없으므로 수정 하지 않음.
				inputName = stN.toUpperCase() + serial;
                                //================================================
                                
				tempStr = tmp[i].substring(quoteIdx, tmp[i].length());
				tempStr = insertDate(tempStr, inputName);
				parserLine = parserLine.append(inputName);
				parserLine = parserLine.append(tempStr);

			} else if (stSelect >= 0) {
				quoteIdx = tmp[i].indexOf("'", stSelect + selectLength);
				if (quoteIdx == -1)
					break;

				stN = tmp[i].substring(stSelect + selectLength, quoteIdx).replaceAll("[0-9]", "");
				stN = stN.trim(); // A~Z
                                
                                //v2 22.정수형 오버플로우_CWE-190 : Update by YOUNGJUN,CHO
                                if ((stSelect + selectLength) < Integer.MAX_VALUE) {
                                    edN = tmp[i].substring(stSelect + selectLength, quoteIdx).replaceAll("[a-zA-Z]", "");    
                                } else {
                                    throw new RuntimeException("DynaMReport addName() 22.정수형 오버플로우_CWE-190");
                                }
                                //================================================
                                
                                //v2 22.정수형 오버플로우_CWE-190 : Update by YOUNGJUN,CHO
                                if (rowNum < Integer.MAX_VALUE) {
                                    serial = Integer.parseInt(edN.trim()) + rowNum; // 숫자
                                } else {
                                    throw new RuntimeException("DynaMReport addName() 22.정수형 오버플로우_CWE-190");
                                }
                                //================================================
                                
				if (i == 0) {
                                    //v2 22.정수형 오버플로우_CWE-190 : Update by YOUNGJUN,CHO
                                    if ((stSelect + selectLength) < Integer.MAX_VALUE) {
                                        parserLine = parserLine.append(tmp[i].substring(0, stSelect + selectLength));
                                    } else {
                                        throw new RuntimeException("DynaMReport addName() 22.정수형 오버플로우_CWE-190");
                                    }
                                    //================================================
                                        
				} else {
					parserLine.append("<td");
					parserLine.append(tmp[i].substring(0, stSelect + selectLength));
				}

				parserLine = parserLine.append(stN.toUpperCase());
				parserLine = parserLine.append(serial);
				parserLine = parserLine.append(tmp[i].substring(quoteIdx, tmp[i].length()));
			} else if (stTextarea >= 0) {
				quoteIdx = tmp[i].indexOf("'", stTextarea + textAreaLength);
				if (quoteIdx == -1)
					break;

				stN = tmp[i].substring(stTextarea + textAreaLength, quoteIdx).replaceAll("[0-9]", "");
				stN = stN.trim(); // A~Z

                                //v2 22.정수형 오버플로우_CWE-190 : Update by YOUNGJUN,CHO
                                if ((stTextarea + textAreaLength) < Integer.MAX_VALUE) {
                                    edN = tmp[i].substring(stTextarea + textAreaLength, quoteIdx).replaceAll("[a-zA-Z]", "");
				} else {
                                    throw new RuntimeException("DynaMReport addName() 22.정수형 오버플로우_CWE-190");
                                }
                                //================================================
                                
                                //v2 22.정수형 오버플로우_CWE-190 : Update by YOUNGJUN,CHO
                                if ((Integer.parseInt(edN.trim()) + rowNum) < Integer.MAX_VALUE) {
                                    serial = Integer.parseInt(edN.trim()) + rowNum; // 숫자
                                } else {
                                        throw new RuntimeException("DynaMReport addName() 22.정수형 오버플로우_CWE-190");
                                }
                                //================================================
                                
				if (i == 0) {
					
                                    //v2 22.정수형 오버플로우_CWE-190 : Update by YOUNGJUN,CHO
                                    if ((stTextarea + textAreaLength) < Integer.MAX_VALUE) {
                                        parserLine = parserLine.append(tmp[i].substring(0, stTextarea + textAreaLength));
                                    } else {
                                        throw new RuntimeException("DynaMReport addName() 22.정수형 오버플로우_CWE-190");
                                    }
                                    //================================================
                                        
				} else {
					parserLine.append("<td");
					parserLine.append(tmp[i].substring(0, stTextarea + textAreaLength));
				}

				parserLine = parserLine.append(stN.toUpperCase());
				parserLine = parserLine.append(serial);
				parserLine = parserLine.append(tmp[i].substring(quoteIdx, tmp[i].length()));
			} else {
				if (i == 0) {
					parserLine = parserLine.append(tmp[i]);
				} else {
					parserLine.append("<td");
					parserLine.append(tmp[i]);
				}
			}
		}
		return parserLine.toString();

	}

	public static String insertDate(String tempStr, String name) {

		int startIndex = 0;
		int endIndex = 0;

		StringBuffer parserLine = new StringBuffer(tempStr);

		String startStr = "showSetWin('dform.";
		String endStr = "');";
		startIndex = startStr.length() + parserLine.indexOf(startStr);
		endIndex = parserLine.indexOf(endStr, startIndex);

		if (startIndex < 0 || endIndex < 0) {
			return parserLine.toString();
		}

		parserLine.delete(startIndex, endIndex);
		parserLine.insert(startIndex, name);

		return parserLine.toString();
	}
}
