/*
 * 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.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.MospException;
import jp.mosp.common.dto.CmAspUserDto;
import jp.mosp.common.dto.CmUserDto;

/**
 * ユーザーテーブルを操作をする機能を提供する。<br><br>
 * {@link CmUserDto}を用いて、DBとJavaプログラム間でレコードを共有する。<br>
 */
public class CmUserDao extends BaseDao {
	
	// テーブル名及びキー列名
	/**
	 *  ユーザー情報テーブル名。<br>
	 */
	public static final String TABLE  = "CM_USER";
	
	/**
	 *  ユーザーテーブル、主キー。<br>
	 */
	public static final String KEY_01 = "USER_ID";
	
	// 列名
	/**
	 *  ユーザーテーブル、列名(ID)。<br>
	 */
	public static final String COL_USER_ID     = "USER_ID";
	
	/**
	 *  ユーザーテーブル、列名(パスワード)。<br>
	 */
	public static final String COL_PASSWORD    = "PASSWORD";
	
	/**
	 *  ユーザーテーブル、列名(社員コード)。<br>
	 */
	public static final String COL_K_CODE      = "K_CODE";
	
	/**
	 *  ユーザーテーブル、列名(ユーザー名)。<br>
	 */
	public static final String COL_USER_NAME   = "USER_NAME";
	
	/**
	 *  ユーザーテーブル、列名(プログラム利用権限)。<br>
	 */
	public static final String COL_AUTHORITY   = "AUTHORITY";
	
	/**
	 *  ユーザーテーブル、列名(データ参照レベル)。<br>
	 */
	public static final String COL_DATA_LEVEL  = "DATA_LEVEL";
	
	/**
	 *  ユーザーテーブル、列名(パスワード変更日)。<br>
	 */
	public static final String COL_CHANGE_PASS = "CHANGE_PASS";
	
	/**
	 *  ユーザーテーブル、列名(削除フラグ)。<br>
	 */
	public static final String COL_DELETE_FLAG = "DELETE_FLAG";
	
	/**
	 * コンストラクタ。<br>
	 */
	public CmUserDao() {
		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 CmUserDao(
			Properties   cfg,
			String       cmd,
			CmAspUserDto aspUser,
			CmUserDto    user,
			Connection   conn
	) {
		this();
		initDao(cfg, cmd, aspUser, user, conn);
	}
	
	/**
	 * 検索結果取得(DTOのList)
	 * @return 検索リスト
	 * @throws SQLException
	 */
	private List<CmUserDto> mappingAll() throws SQLException {
		List<CmUserDto> all = new ArrayList<CmUserDto>();
		while (rs.next()) {
			all.add(mapping());
		}
		return all;
	}
	
	/**
	 * 検索結果取得(DTO)
	 * @return レコード(DTO)
	 * @throws SQLException
	 */
	private CmUserDto mapping() throws SQLException {
		CmUserDto dto = new CmUserDto();
		dto.setUserId    (rs.getString(COL_USER_ID    ));
		dto.setPassword  (rs.getString(COL_PASSWORD   ));
		dto.setKCode     (rs.getString(COL_K_CODE     ));
		dto.setUserName  (rs.getString(COL_USER_NAME  ));
		dto.setAuthority (rs.getString(COL_AUTHORITY  ));
		dto.setDataLevel (rs.getInt   (COL_DATA_LEVEL ));
		dto.setChangePass(rs.getDate  (COL_CHANGE_PASS));
		dto.setDeleteFlag(rs.getInt   (COL_DELETE_FLAG));
		mappingCommonInfo(dto);
		return dto;
	}
	
	
	/**
	 * 全データ取得。<br>
	 * @return 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<CmUserDto> findAllCmUser() throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			prepareStatement(getSelectQuery(getClass()) + getOrderForKey(getClass()));
			executeQuery();
			return mappingAll();
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	
	/**
	 * キーによるデータ取得。<br>
	 * @param userId ユーザーID(検索キー)
	 * @return 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public CmUserDto findForKey(String userId) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()));
			setParam(index++, userId);
			executeQuery();
			CmUserDto cmUserDto = null;
			if (rs.next()) {
				cmUserDto = mapping();
			}
			return cmUserDto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	
	/**
	 * キーによる行ロック取得。<br>
	 * @param userId ユーザーID(検索キー)
	 * @return 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public CmUserDto findForUpdate(String userId) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()) + getForUpdate());
			setParam(index++, userId);
			executeQuery();
			CmUserDto cmUserDto = null;
			if (rs.next()) {
				cmUserDto = mapping();
			}
			return cmUserDto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	
	/**
	 * 条件文によるデータ取得。<br>
	 * @param userId 検索ユーザーID
	 * @param userName 検索ユーザー名
	 * @param authority 検索MosP利用権限
	 * @param deleteFlag 検索削除フラグ
	 * @return 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<CmUserDto> findCmUserForCondition(
			String userId,
			String userName,
			String authority,
			String deleteFlag
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append("WHERE ");
		sb.append(COL_USER_ID);
		sb.append(" LIKE ? AND ");
		sb.append(COL_USER_NAME);
		sb.append(" LIKE ? ");
		this.pob.appendLike(COL_USER_ID);
		this.pob.appendLike(COL_USER_NAME);
		if (!authority.equals("")) {
			sb.append("AND ");
			sb.append(COL_AUTHORITY);
			sb.append(" = ? ");
			this.pob.appendWhere(COL_AUTHORITY, Query.FilterOperator.EQUAL);
		}
		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()));
			setParam(index++, userId + "%");
			setParam(index++, "%" + userName + "%");
			if (!authority.equals("")) {
				setParam(index++, authority);
			}
			if (!deleteFlag.equals("")) {
				setParam(index++, Integer.parseInt(deleteFlag));
			}
			executeQuery();
			return mappingAll();
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	
	/**
	 * データ挿入。<br>
	 * @param dto 挿入対象DTO
	 * @return 挿入結果(件数)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws MospException
	 */
	public int insert(CmUserDto 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(CmUserDto dto) throws SQLException, IllegalAccessException, NoSuchFieldException, MospException {
		try {
			index = 1;
			prepareStatement(getUpdateQuery(getClass()));
			setParams(dto, false);
			setParam(index++, dto.getUserId());
			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(CmUserDto dto, boolean isInsert) throws SQLException {
		setParam(index++, dto.getUserId    ());
		setParam(index++, dto.getPassword  ());
		setParam(index++, dto.getKCode     ());
		setParam(index++, dto.getUserName  ());
		setParam(index++, dto.getAuthority ());
		setParam(index++, dto.getDataLevel ());
		setParam(index++, dto.getChangePass());
		setParam(index++, dto.getDeleteFlag());
		setCommonParams(isInsert);
	}
	
}
