/*
 * MosP - Mind Open Source Project    http://www.mosp.jp/
 * Copyright (C) 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.common.dao;

import jp.getset.gae.bigtable.PreparedStatement;
import jp.getset.gae.driver.java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import com.google.appengine.api.datastore.Query;

import jp.mosp.common.common.BaseDao;
import jp.mosp.common.common.MospConst;
import jp.mosp.common.common.MospException;
import jp.mosp.common.dto.CmAspUserDto;
import jp.mosp.common.dto.CmCodeDto;
import jp.mosp.common.dto.CmUserDto;

/**
 * コードテーブルを操作をする機能を提供する。<br><br>
 * {@link CmCodeDto}を用いて、DBとJavaプログラム間でレコードを共有する。<br>
 */
public class CmCodeDao extends BaseDao {
	
	// テーブル名及びキー列名
	/**
	 *  コードテーブル名。<br>
	 */
	public static final String TABLE  = "CM_CODE";
	
	/**
	 *  コードテーブル、主キー1。<br>
	 */
	public static final String KEY_01 = "T_ID";
	
	/**
	 *  コードテーブル、主キー2。<br>
	 */
	public static final String KEY_02 = "T_CODE";
	
	// 列名
	/**
	 *  コードテーブル、列名(コードID)。<br>
	 */
	public static final String COL_T_ID        = "T_ID";
	
	/**
	 *  コードテーブル、列名(コード)。<br>
	 */
	public static final String COL_T_CODE      = "T_CODE";
	
	/**
	 *  コードテーブル、列名(名称)。<br>
	 */
	public static final String COL_T_NAME      = "T_NAME";
	
	/**
	 *  コードテーブル、列名(表示順)。<br>
	 */
	public static final String COL_VIEW_INDEX  = "VIEW_INDEX";
	
	/**
	 *  コードテーブル、列名(削除フラグ)。<br>
	 */
	public static final String COL_DELETE_FLAG = "DELETE_FLAG";
	
	/**
	 * コンストラクタ。<br>
	 */
	public CmCodeDao() {
		super();
		INSERT_DATE = "INSERT_DATE";
		INSERT_USER = "INSERT_USER";
		UPDATE_DATE = "UPDATE_DATE";
		UPDATE_USER = "UPDATE_USER";
	}
	
	/**
	 * コンストラクタ。<br>
	 * @param cfg     設定ファイル
	 * @param cmd     コマンド
	 * @param aspUser ASPユーザー
	 * @param user    ユーザー
	 * @param conn    DBコネクション
	 */
	public CmCodeDao(
			Properties   cfg,
			String       cmd,
			CmAspUserDto aspUser,
			CmUserDto    user,
			Connection   conn
	) {
		this();
		initDao(cfg, cmd, aspUser, user, conn);
	}
	
	/**
	 * 検索結果取得(DTOのList)
	 * @return 検索リスト
	 * @throws SQLException
	 */
	private List<CmCodeDto> mappingAll() throws SQLException {
		List<CmCodeDto> all = new ArrayList<CmCodeDto>();
		while (rs.next()) {
			all.add(mapping());
		}
		return all;
	}
	
	/**
	 * 検索結果取得(DTOのList)(findAllTId用)
	 * @return 検索リスト
	 * @throws SQLException
	 */
	private List<CmCodeDto> mappingAllTId() throws SQLException {
		List<CmCodeDto> all = new ArrayList<CmCodeDto>();
		while (rs.next()) {
			CmCodeDto dto = new CmCodeDto();
			dto.setTId(rs.getString(COL_T_ID));
			all.add(dto);
		}
		return all;
	}
	
	/**
	 * 検索結果取得(DTO)
	 * @return レコード(DTO)
	 * @throws SQLException
	 */
	private CmCodeDto mapping() throws SQLException {
		CmCodeDto dto = new CmCodeDto();
		dto.setTId(rs.getString(COL_T_ID));
		dto.setTCode(rs.getString(COL_T_CODE));
		dto.setTName(rs.getString(COL_T_NAME));
		dto.setViewIndex(rs.getInt(COL_VIEW_INDEX));
		dto.setDeleteFlag(rs.getInt(COL_DELETE_FLAG));
		mappingCommonInfo(dto);
		return dto;
	}
	
	/**
	 * 全データ取得。<br>
	 * @return 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<CmCodeDto> findAll() throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			prepareStatement(getSelectQuery(getClass()) + getOrderForKey(getClass()));
			executeQuery();
			List<CmCodeDto> all = mappingAll();
			return all;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 全データ取得(T_IDのリスト)。<br>
	 * @return 検索結果(DTOのList)
	 * @throws SQLException
	 */
	public List<CmCodeDto> findAllTId() throws SQLException {
		try {
			StringBuffer sb = new StringBuffer();
			sb.append("SELECT DISTINCT ");
			sb.append(COL_T_ID + " ");
			sb.append("FROM ");
			sb.append(TABLE + " ");
			this.setPreparedStatement(PreparedStatement.Mode.SELECT, getClass());
			this.pob.appendDistinct(COL_T_ID);
			prepareStatement(sb.toString());
			executeQuery();
			List<CmCodeDto> all = mappingAllTId();
			return all;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * キーによるデータ取得。<br>
	 * @param tId   コード区分(検索キー)
	 * @param tCode コード(検索キー)
	 * @return 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public CmCodeDto findForKey(String tId, String tCode) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()));
			setParam(index++, tId);
			setParam(index++, tCode);
			executeQuery();
			CmCodeDto CmCodeDto = null;
			if (rs.next()) {
				CmCodeDto = mapping();
			}
			return CmCodeDto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	
	/**
	 * キーによる行ロック取得。<br>
	 * @param tId   コード区分(検索キー)
	 * @param tCode コード(検索キー)
	 * @return 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public CmCodeDto 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();
			CmCodeDto CmCodeDto = null;
			if (rs.next()) {
				CmCodeDto = mapping();
			}
			return CmCodeDto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	
	/**
	 * 条件文によるデータ取得。<br>
	 * @param tId        コード区分(検索キー)
	 * @return 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<CmCodeDto> findForCondition(String tId) throws SQLException, IllegalAccessException, NoSuchFieldException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append("WHERE ");
		sb.append(COL_T_ID);
		sb.append(" = ? AND ");
		sb.append(COL_DELETE_FLAG);
		sb.append(" = ? ");
		this.pob.appendWhere(COL_T_ID, Query.FilterOperator.EQUAL);
		this.pob.appendWhere(COL_DELETE_FLAG, Query.FilterOperator.EQUAL);
		this.pob.appendSort(COL_VIEW_INDEX);
		this.pob.appendSort(COL_T_ID);
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + "ORDER BY " + COL_VIEW_INDEX + ", " + COL_T_ID);
			setParam(index++, tId);
			setParam(index++, MospConst.DELETE_FLAG_OFF);
			executeQuery();
			List<CmCodeDto> list = mappingAll();
			return list;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 条件文によるデータ取得(検索用)。<br>
	 * @param tId        コード区分(検索キー)
	 * @param tCode      コード(検索キー)
	 * @param tName      コード名称(検索キー)
	 * @param deleteFlag 削除フラグ(検索キー)
	 * @return 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<CmCodeDto> findForSearch(
			String tId,
			String tCode,
			String tName,
			String deleteFlag
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append("WHERE ");
		if (!tId.equals("")) {
			sb.append(COL_T_ID);
			sb.append(" = ? AND ");
			this.pob.appendWhere(COL_T_ID, Query.FilterOperator.EQUAL);
		}
		if (!tCode.equals("")) {
			sb.append(COL_T_CODE);
			sb.append(" LIKE ? ");
			sb.append("AND ");
			this.pob.appendLike(COL_T_CODE);
		}
		sb.append(COL_T_NAME);
		sb.append(" LIKE ? ");
		this.pob.appendLike(COL_T_NAME);
		if (!deleteFlag.equals("")) {
			sb.append("AND ");
			sb.append(COL_DELETE_FLAG);
			sb.append(" = ? ");
			this.pob.appendWhere(COL_DELETE_FLAG, Query.FilterOperator.EQUAL);
		}
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			if (!tId.equals("")) {
				setParam(index++, tId);
			}
			if (!tCode.equals("")) {
				setParam(index++, tCode + "%");
			}
			setParam(index++, "%" + tName + "%");
			if (!deleteFlag.equals("")) {
				setParam(index++, Integer.parseInt(deleteFlag));
			}
			executeQuery();
			List<CmCodeDto> list = mappingAll();
			return list;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * データ挿入。<br>
	 * @param dto 挿入対象DTO
	 * @return 挿入結果(件数)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws MospException
	 */
	public int insert(CmCodeDto 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();
		}
	}
	
	
	/**
	 * データ更新。<br>
	 * @param dto 更新対象DTO
	 * @return 更新結果(件数)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws MospException
	 */
	public int update(CmCodeDto 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
	 * @param isInsert 挿入文フラグ(true：挿入文、false：更新文)
	 * @throws SQLException
	 */
	private void setParams(CmCodeDto dto, boolean isInsert) throws SQLException {
		setParam(index++, dto.getTId());
		setParam(index++, dto.getTCode());
		setParam(index++, dto.getTName());
		setParam(index++, dto.getViewIndex());
		setParam(index++, dto.getDeleteFlag());
		setCommonParams(isInsert);
	}
}
