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

package kr.co.kihyun.beans.totsys.doc.table.item;

import java.sql.*;
import java.util.ArrayList;
import kr.co.kihyun.beans.entity.MoumiEntity;
import kr.co.kihyun.beans.entity.TotItem;
import kr.co.kihyun.beans.entity.TotItemType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import kr.co.kihyun.db.*;

public class Item extends DBManager {
	private static final Logger LOG = LoggerFactory.getLogger(Item.class);

	private ResultSet rs = null;

	// /////////////////////////////////// 공통 메소드 /////////////////////////////////////

	/******** 프로젝트 목록을 배열에 입력 ********/
	public int[] getType(Long docID) throws NumberFormatException {
		StringBuilder sql = new StringBuilder(150);

		int count = 0;
		int[] type = null;
		String[] typeName = null;
		try {
			sql.append("select type from ").append(MoumiEntity.getTableName(TotItem.class))
					.append(" where doc_id=? order by num asc");

			rs = execQuery(sql.toString(), docID);
			if (rs != null) {
				rs.last();
				count = rs.getRow();
				rs.beforeFirst();
			} else {
				return null;
			}

			type = new int[count];
			typeName = new String[count];

			for (int i = 0; rs.next(); i++) {
				type[i] = rs.getInt(1);
				typeName[i] = TotItemType.values()[type[i]].name();
			}

			return type;
		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nMySQL Error Code - {}\nmessage - {}\nsql - {}",
					new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}

	public int[] getInTypeList(Long docID) throws NumberFormatException {
		StringBuilder sql = new StringBuilder(150);

		int count = 0;
		int[] type = null;
		String[] typeName = null;
		try {
			sql.append("select type from ").append(MoumiEntity.getTableName(TotItem.class))
					.append(" where doc_id=? and type > 0 order by num asc");

			rs = execQuery(sql.toString(), docID);
			if (rs != null) {
				rs.last();
				count = rs.getRow();
				rs.beforeFirst();
			} else {
				return null;
			}

			type = new int[count];
			typeName = new String[count];

			for (int i = 0; rs.next(); i++) {
				type[i] = rs.getInt(1);
				typeName[i] = TotItemType.values()[type[i]].name();
			}

			return type;
		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nMySQL Error Code - {}\nmessage - {}\nsql - {}",
					new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}

	/********** 입력 할수 있는 item count **********/
	public int getInCount(Long docID) throws NumberFormatException {
		StringBuilder sql = new StringBuilder(120);

		int inItemCount = 0;

		try {
			sql.append("select count(num) from ").append(MoumiEntity.getTableName(TotItem.class))
					.append(" where des='empty' and doc_id=?");

			rs = execQuery(sql.toString(), docID);
			if (rs.next()) {
				inItemCount = rs.getInt(1);
			}

			return inItemCount;
		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nMySQL Error Code - {}\nmessage - {}\nsql - {}",
					new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}

	// /////////////////////////////////// 정적인 표에만 쓰임 /////////////////////////////////////

	// 정적인표의 입력 item name list
	public String[] getInNameList(Long docID) {
		StringBuilder sql = new StringBuilder(150);

		String[] inName = null;
		int count = -1;
		try {
			sql.append("select name from ").append(MoumiEntity.getTableName(TotItem.class))
					.append(" where des='empty' and doc_id=? order by num asc");

			rs = execQuery(sql.toString(), docID);
			if (rs != null) {
				rs.last();
				count = rs.getRow();
				rs.beforeFirst();
			} else {
				return null;
			}

			inName = new String[count];

			for (int i = 0; rs.next(); i++) {
				inName[i] = rs.getString(1);
			}

			return inName;
		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nMySQL Error Code - {}\nmessage - {}\nsql - {}",
					new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}

	// /////////////////////////////////// 동적인 표에만 쓰임 /////////////////////////////////////

	/********** 타이틀 행 수 **********/
	public int[] getTitleRowCountList(Long docID) {
		int[] titleRowCountList = null;
		int tableCount = 0;

		tableCount = getTableCount(docID); // 임시 사용
		titleRowCountList = new int[tableCount];

		for (int t = 0; t < tableCount; t++) {
			titleRowCountList[t] = getTitleRowCount(docID, (t + 1)); // table num은 1부터 시작 하니까 i+1를 해줘야함
		}

		return titleRowCountList;
	}

	public int getTitleRowCount(Long docID) {
		return getTitleRowCount(docID, 1);
	}

	public int getTitleRowCount(Long docID, int tableNum) {
		StringBuilder sql = new StringBuilder(120);

		int strRowNum = 0;
		int endRowNum = 0;

		int titleCount = -1;

		try {
			sql.append("select min(row_num) from ").append(MoumiEntity.getTableName(TotItem.class))
					.append(" where doc_id=? and table_num=?");
			rs = execQuery(sql.toString(), docID, tableNum);
			if (rs.next()) {
				strRowNum = rs.getInt(1);
			}

			rs.close();
			execClose();

			sql = new StringBuilder(120).append("select min(row_num) from ").append(MoumiEntity.getTableName(TotItem.class))
					.append(" where doc_id=? and table_num=? and des='empty'");
			rs = execQuery(sql.toString(), docID, tableNum);
			if (rs.next()) {
				endRowNum = rs.getInt(1);
			}
			titleCount = endRowNum - strRowNum;
			return titleCount;
		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nMySQL Error Code - {}\nmessage - {}\nsql - {}",
					new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}

	/********** 입력 할 수 있는 첫번째 행 번호 **********/
	public int getInRowNum(Long docID) {
		StringBuilder sql = new StringBuilder(120);

		int rowNum = 0;

		try {
			sql.append("select min(row_num) from ").append(MoumiEntity.getTableName(TotItem.class))
					.append(" where des='empty' and doc_id=?");

			rs = execQuery(sql.toString(), docID);
			if (rs.next()) {
				rowNum = rs.getInt(1);
			}

			return rowNum;
		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nMySQL Error Code - {}\nmessage - {}\nsql - {}",
					new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}

	// 동적인표에서 타이틀 행이 아닌 입력할 수 있는 첫번째 행의 첫번째 item number value 추출
	public int getStartInNum(Long docID) {
		int rowNum = getInRowNum(docID);
		int num = getNum(docID, rowNum);

		return num;
	}

	public int getStartInNum(Long docID, boolean isDynaTable) {
		int num = 0;
		if (isDynaTable) {
			num = getStartInNum(docID);
		} else {
			num = 0;
		}

		return num;
	}

	// 행의 첫번째 열의 item number 값 추출
	public int getNum(Long docID, int rowNum) {
		StringBuilder sql = new StringBuilder(120);

		int itemNum = 0;

		try {
			sql.append("select num from ").append(MoumiEntity.getTableName(TotItem.class))
					.append(" where row_num=? and doc_id=? order by num asc");
			rs = execQuery(sql.toString(), rowNum, docID);
			if (rs.next()) {
				itemNum = rs.getInt(1);
			}

			return itemNum;
		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nMySQL Error Code - {}\nmessage - {}\nsql - {}",
					new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}

	public Long getTotItemID(Long docID, int num) {
		StringBuilder sql = new StringBuilder(90);

		Long id = null;
		ArrayList<Object> paramList = new ArrayList<Object>();

		try {
			sql.append("select id from ").append(MoumiEntity.getTableName(TotItem.class)).append(" where doc_id=? and num=?");
			paramList.add(docID);
			paramList.add(num);

			rs = execQuery(sql.toString(), paramList.toArray());
			if (rs.next()) {
				id = rs.getLong(1);
			}
			return id;
		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nMySQL Error Code - {}\nmessage - {}\nsql - {}",
					new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}

	// 행의 첫번째 열의 item number 값 추출
	public int getStartIndex(Long docID) {
		StringBuilder sql = new StringBuilder(90);

		int itemNum = 0;

		try {
			// DB에서 가저올 행 수 알아내기
			sql .append("select num from ").append(MoumiEntity.getTableName(TotItem.class))
					.append(" where type > 0 and doc_id=? order by num asc");
			rs = execQuery(sql.toString(), docID);
			if (rs.next()) {
				itemNum = rs.getInt(1);
			}

			return itemNum;
		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nMySQL Error Code - {}\nmessage - {}\nsql - {}",
					new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}

	// 행의 첫번째 열의 item number 값 추출
	public String[] getTitleDataList(Long docID) {
		int endRowNum = getTitleRowCount(docID);
		return getTitleDataList(docID, endRowNum);
	}

	public String[] getTitleDataList(Long docID, int endRowNum) {
		StringBuilder sql = new StringBuilder(90);

		String[] titleDataList = null;
		int count = 0;

		try {
			sql.append("select des from ").append(MoumiEntity.getTableName(TotItem.class))
					.append(" where row_num <= ? and doc_id=? order by num asc");

			rs = execQuery(sql.toString(), endRowNum, docID);
			if (rs != null) {
				rs.last();
				count = rs.getRow();
				rs.beforeFirst();
			} else {
				return null;
			}

			titleDataList = new String[count];

			for (int i = 0; rs.next(); i++) {
				titleDataList[i] = rs.getString(1);
			}

			return titleDataList;
		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nMySQL Error Code - {}\nmessage - {}\nsql - {}",
					new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}

	public int getTableCount(Long docID) {
		int tableCount = 1;
		StringBuilder sql = new StringBuilder(90);

		try {
			/******** new doc id ********/
			sql.append("select max(table_num) from ").append(MoumiEntity.getTableName(TotItem.class))
					.append(" where doc_id=?");
			rs = execQuery(sql.toString(), docID);
			if (rs.next()) {
				tableCount = rs.getInt(1);
			}

			return tableCount;
		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nMySQL Error Code - {}\nmessage - {}\nsql - {}",
					new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}

	/********** 입력 할수 있는 row count **********/
	public int[] getInRowCountList(Long docID) {
		int[] inRowCountList = null;
		int tableCount = 0;

		tableCount = getTableCount(docID); // 임시 사용
		inRowCountList = new int[tableCount];

		for (int t = 0; t < tableCount; t++) {
			inRowCountList[t] = getInRowCount(docID, (t + 1)); // table num은 1부터 시작 하니까 i+1를 해줘야함
		}

		return inRowCountList;
	}

	public int getInRowCount(Long docID) throws NumberFormatException {
		return getInRowCount(docID, 1);
	}

	public int getInRowCount(Long docID, int tableNum) {
		StringBuilder sql = new StringBuilder(120);

		int inRowCount = 0;

		try {
			// DB에서 가저올 행 수 알아내기
			sql.append("select count(distinct(row_num)) from ").append(MoumiEntity.getTableName(TotItem.class))
					.append(" where des='empty' and doc_id=? and table_num=?");

			rs = execQuery(sql.toString(), docID, tableNum);
			if (rs.next()) {
				inRowCount = rs.getInt(1);
			}

			return inRowCount;
		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nMySQL Error Code - {}\nmessage - {}\nsql - {}",
					new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}
}
