/*
 * MosP - Mind Open Source Project         http://www.mosp.jp/
 * Copyright (C) 1987-2008 MIND Co., Ltd.  http://www.e-mind.co.jp/
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package jp.mosp.system.dao;

import java.sql.SQLException;
import java.util.ArrayList;

import java.util.List;

import jp.mosp.system.dto.MCodeDto;
import jp.mosp.common.common.BaseDao;
import jp.mosp.common.common.MospException;

public class MCodeDao extends BaseDao {

	// テーブル名及びキー列名
	public static final String TABLE	= "M_CODE";
	public static final String KEY_1	= "TID";	//コード名
	public static final String KEY_2	= "TCODE";	//コード

	// 列名
	public static final String COL_TID  		= "TID";		//コード名
	public static final String COL_TCODE  	= "TCODE";		//コード
	public static final String COL_TNAME  	= "TNAME";		//コード名称
	public static final String COL_TCHANGE	= "TCHANGE";	//コード変換

	/**
	 * コンストラクタ
	 */
	public MCodeDao() {
		super();
	}

	/**
	 * 検索結果取得(DTOのList)
	 * @return List 検索リスト
	 * @throws SQLException
	 */
	private List<MCodeDto> mappingAll() throws SQLException {
		List<MCodeDto> all = new ArrayList<MCodeDto>();
		while (rs.next()) {
			all.add(mapping());
		}
		return all;
	}

	/**
	 * 検索結果取得(DTO)
	 * @return m_codeDto m_codeレコード
	 * @throws SQLException
	 */
	private MCodeDto mapping() throws SQLException {
		MCodeDto dto = new MCodeDto();
		dto.setTId 		(rs.getString (COL_TID));		//コード名
		dto.setTCode 	(rs.getString (COL_TCODE));		//コード
		dto.setTName 	(rs.getString (COL_TNAME));		//コード名称
		dto.setTChange 	(rs.getString (COL_TCHANGE));	//コード変換
		return dto;
	}

	/**
	 * 全データ取得
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List findAll() throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			prepareStatement(getSelectQuery(getClass()) + getOrderForKey(getClass()));
			executeQuery();
			List all = mappingAll();
			return all;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * 検索結果取得(DTOのList)(findAllTId用)
	 * @return 検索リスト
	 * @throws SQLException
	 */
	private List<MCodeDto> mappingAllTId() throws SQLException {
		List<MCodeDto> all = new ArrayList<MCodeDto>();
		while (rs.next()) {
			MCodeDto dto = new MCodeDto();
			dto.setTId(rs.getString(COL_TID));
			all.add(dto);
		}
		return all;
	}

	/**
	 * キーによるデータ取得
	 * @param tid コード名(検索キー)
	 * @param tcode コード(検索キー)
	 * @return m_codeDto 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public MCodeDto findForKey(
			String tid,
			String tcode
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()));
			setParam(index++, tid);
			setParam(index++, tcode);
			executeQuery();
			MCodeDto dto = null;
			if (rs.next()) {
				dto = mapping();
				mappingCommonInfo(dto);
			}
			return dto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * キーによる行ロック取得
	 * @param tid コード名(検索キー)
	 * @param tcode コード(検索キー)
	 * @return m_codeDto 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public MCodeDto findForUpdate(
			String tid,
			String tcode
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()) + getForUpdate());
			setParam(index++, tid);
			setParam(index++, tcode);
			executeQuery();
			MCodeDto dto = null;
			if (rs.next()) {
				dto = mapping();
				mappingCommonInfo(dto);
			}
			return dto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * 条件文による行ロック
	 * @param tid 検索コード名
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public void findForUpdate(
			String tid
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append("WHERE ");
		sb.append(COL_TID);
		sb.append(" = ? ");
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getForUpdate());
			setParam(index++, tid);
			executeQuery();
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * 条件文によるデータ取得
	 * @param tid 検索コード名
	 * @param tcode 検索コード
	 * @return List 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<MCodeDto> findForCondition(
			String tid,
			String tcode
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append("WHERE ");
		sb.append(COL_TID);
		sb.append(" = ? AND ");
		sb.append(COL_TCODE);
		sb.append(" = ? ");
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			setParam(index++, tid);
			setParam(index++, tcode + "%");
			executeQuery();
			List<MCodeDto> list = mappingAll();
			return list;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * 条件文によるデータ取得
	 * @param tid 検索コード名
	 * @return list 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<MCodeDto> findForHoliday(
			String tid
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append("WHERE ");
		sb.append(COL_TID);
		sb.append(" = ? AND ");
		sb.append(COL_TCODE);
		sb.append(" != '' ");
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			setParam(index++, tid);
			executeQuery();
			List<MCodeDto> list = mappingAll();
			return list;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * 条件文によるデータ取得
	 * @param tid 検索コード名
	 * @return list 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<MCodeDto> findForCondition(
			String tid
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append("WHERE ");
		sb.append(COL_TID);
		sb.append(" = ? ");
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			setParam(index++, tid);
			executeQuery();
			List<MCodeDto> list = mappingAll();
			return list;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * 条件文によるデータ取得
	 * @param tid 検索コード名
	 * @return dto 検索結果DTO
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public MCodeDto findForDto(
			String tid
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append("WHERE ");
		sb.append(COL_TID);
		sb.append(" = ? ");
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			setParam(index++, tid);
			executeQuery();
			MCodeDto dto = null;
			if (rs.next()) {
				dto = mapping();
			}
			return dto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * 条件文によるデータ取得(検索用)
	 * @param tId        コード区分(検索キー)
	 * @param tCode      コード(検索キー)
	 * @param tName      コード名称(検索キー)
	 * @return 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<MCodeDto> findForSearch(
			String tId,
			String tCode,
			String tName
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append("WHERE ");
		if (!tId.equals("")) {
			sb.append(COL_TID);
			sb.append(" = ? AND ");
		}
		if (!tCode.equals("")) {
			sb.append(COL_TCODE);
			sb.append(" LIKE ? ");
			sb.append("AND ");
		}
		sb.append(COL_TNAME);
		sb.append(" LIKE ? ");
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			if (!tId.equals("")) {
				setParam(index++, tId);
			}
			if (!tCode.equals("")) {
				setParam(index++, tCode + "%");
			}
			setParam(index++, "%" + tName + "%");
			executeQuery();
			List<MCodeDto> list = mappingAll();
			return list;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * 条件文によるデータ取得(検索用)
	 * @param tId        コード区分(検索キー)
	 * @param tCode      コード(検索キー)
	 * @param tName      コード名称(検索キー)
	 * @return 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<MCodeDto> findForHoliday(
			String tId,
			String tCode,
			String tName
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append("WHERE ");
		sb.append(COL_TID);
		sb.append(" = ? ");
		if (!tCode.equals("")) {
			sb.append(" AND ");
			sb.append(COL_TCODE);
			sb.append(" LIKE ? ");
		}
		sb.append(" AND ");
		sb.append(COL_TNAME);
		sb.append(" LIKE ? ");
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			setParam(index++, tId);
			if (!tCode.equals("")) {
				setParam(index++,"%" + tCode + "%");
			}
			setParam(index++, "%" + tName + "%");
			executeQuery();
			List<MCodeDto> list = mappingAll();
			return list;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * 全データ取得(T_IDのリスト)
	 * @return 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<MCodeDto> findAllTId() throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			StringBuffer sb = new StringBuffer();
			sb.append("SELECT DISTINCT ");
			sb.append(COL_TID);
			sb.append(" FROM ");
			sb.append(TABLE + " ");
			prepareStatement(sb.toString());
			executeQuery();
			List<MCodeDto> all = mappingAllTId();
			return all;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * 条件文によるデータ取得
	 * @param tid 検索コード名
	 * @return list 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<MCodeDto> findForReason(
			String tid
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append("WHERE ");
		sb.append(COL_TID);
		sb.append(" = ? AND ");
		sb.append(COL_TNAME);
		sb.append(" != '' ");
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			setParam(index++, tid);
			executeQuery();
			List<MCodeDto> list = mappingAll();
			return list;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * データ挿入
	 * @param dto 挿入対象DTO
	 * @return int 挿入結果(件数)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws MospException
	 */
	public int insert(MCodeDto dto) throws SQLException, IllegalAccessException, NoSuchFieldException, MospException {
		try {
			index = 1;
			prepareStatement(getInsertQuery(getClass()));
			setParams(dto,true);
			executeUpdate();
			chkInsert(1);
			return cnt;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * データ更新
	 * @param dto 更新対象DTO
	 * @return int 更新結果(件数)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws MospException
	 */
	public int update(MCodeDto dto) throws SQLException, IllegalAccessException, NoSuchFieldException, MospException {
		try {
			index = 1;
			prepareStatement(getUpdateQuery(getClass()));
			setParams(dto,false);
			setParam(index++, dto.getTId());
			setParam(index++, dto.getTCode());
			executeUpdate();
			chkUpdate(1);
			return cnt;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * データ削除
	 * @param dto 更新対象DTO
	 * @return int 削除結果(件数)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws MospException
	 */
	public int delete(MCodeDto dto) throws SQLException, IllegalAccessException, NoSuchFieldException, MospException {
		try {
			index = 1;
			prepareStatement(getDeleteQuery(getClass()));
			setParam(index++, dto.getTId());
			setParam(index++, dto.getTCode());
			executeUpdate();
			chkDelete(1);
			return cnt;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * データ削除
	 * @param tid 更新対象TID
	 * @return int 削除結果(件数)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws MospException
	 */
	public int delete(String tid) throws SQLException, IllegalAccessException, NoSuchFieldException, MospException {
		try {
			index = 1;
			StringBuffer sb = new StringBuffer();
			sb.append("DELETE FROM ");
			sb.append(TABLE);
			sb.append(" WHERE ");
			sb.append(COL_TID);
			sb.append(" = ? ");
			prepareStatement(sb.toString());
			setParam(index++, tid);
			executeUpdate();
			//chkDelete(1);
			return cnt;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * パラメータ設定
	 * @param dto 更新対象DTO
	 * @throws SQLException
	 */
	private void setParams(MCodeDto dto, boolean isInsert) throws SQLException {
		setParam(index++, dto.getTId());		//コード名
		setParam(index++, dto.getTCode());		//コード
		setParam(index++, dto.getTName());		//コード名称
		setParam(index++, dto.getTChange());	//コード変換
		setCommonParams(isInsert);
	}

	/**
	 * テーブルロック
	 * @param 	tid	更新対象テーブルID
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public void tableLock(String tid) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			if (conn.getMetaData().getDatabaseProductName().equals("MySQL")) {
				// DBがMySQLの場合は行ロック
				findForUpdate(tid);
			} else {
				// DBがPostgreSQLの場合はテーブルロック
				StringBuffer sb = new StringBuffer();
				sb.append("LOCK TABLE ");
				sb.append(TABLE);
				prepareStatement(sb.toString());
				executeUpdate();
			}
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

}
