/*
 * 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.common.dao;

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

import jp.mosp.common.common.MospException;
import jp.mosp.common.dto.MosPUserDto;

public class MosPUserDao extends MosPDao {

	// テーブル名及びキー列名
	public static final String TABLE  = "CM_USER";
	public static final String KEY_01 = "USER_ID";

	// 列名
	public static final String COL_USER_ID     = "USER_ID";
	public static final String COL_PASSWORD    = "PASSWORD";
	public static final String COL_K_CODE      = "K_CODE";
	public static final String COL_USER_NAME   = "USER_NAME";
	public static final String COL_AUTHORITY   = "AUTHORITY";
	public static final String COL_DATA_LEVEL  = "DATA_LEVEL";
	public static final String COL_CHANGE_PASS = "CHANGE_PASS";
	public static final String COL_DELETE_FLAG = "DELETE_FLAG";

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

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

	/**
	 * 検索結果取得(DTO)
	 * @return	dto	検索結果DTO
	 * @throws SQLException
	 */
	private MosPUserDto mapping() throws SQLException {
		MosPUserDto dto = new MosPUserDto();
		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;
	}

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

	/**
	 * キーによるデータ取得
	 * @param userId ユーザーID(検索キー)
	 * @return 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public MosPUserDto findForKey(String userId) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			prepareStatement(getSelectQuery(getClass()) + getConditionForKey(getClass()));
			setParam(index++, userId);
			executeQuery();
			MosPUserDto MosPUserDto = null;
			if (rs.next()) {
				MosPUserDto = mapping();
			}
			return MosPUserDto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

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

	/**
	 * 条件文によるデータ取得
	 * @param userId 検索ユーザーID
	 * @param userName 検索ユーザー名
	 * @param mospAuthority 検索MosP利用権限
	 * @param deleteFlag 検索削除フラグ
	 * @return 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List findForCondition(
			String userId,
			String userName,
			String mospAuthority,
			String deleteFlag
	) throws SQLException, IllegalAccessException, NoSuchFieldException {
		index = 1;
		StringBuffer sb = new StringBuffer();
		sb.append("WHERE ");
		sb.append(COL_USER_ID);
		sb.append(" <> 'admin' AND ");
		sb.append(COL_USER_ID);
		sb.append(" LIKE ? AND ");
		sb.append(COL_USER_NAME);
		sb.append(" LIKE ? ");
		if (!mospAuthority.equals("")) {
			sb.append("AND ");
			sb.append(COL_AUTHORITY);
			sb.append(" = ? ");
		}
		if (!deleteFlag.equals("")) {
			sb.append("AND ");
			sb.append(COL_DELETE_FLAG);
			sb.append(" = ? ");
		}
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			setParam(index++, userId + "%");
			setParam(index++, "%" + userName + "%");
			if (!mospAuthority.equals("")) {
				setParam(index++, mospAuthority);
			}
			if (!deleteFlag.equals("")) {
				setParam(index++, Integer.parseInt(deleteFlag));
			}
			executeQuery();
			List listMosPUser = mappingAll();
			return listMosPUser;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * キーによるデータ取得
	 * @param userId ユーザーID(検索キー)
	 * @return 検索結果(DTO)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public MosPUserDto findForRegistered(String userId) throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			index = 1;
			StringBuffer sb = new StringBuffer();
			sb.append("WHERE ");
			sb.append(COL_USER_ID);
			sb.append(" LIKE ? ");
			sb.append(" AND ");
			sb.append(COL_DELETE_FLAG);
			sb.append(" = 0 ");
			prepareStatement(getSelectQuery(getClass()) + sb.toString());
			setParam(index++, userId);
			executeQuery();
			MosPUserDto MosPUserDto = null;
			if (rs.next()) {
				MosPUserDto = mapping();
			}
			return MosPUserDto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}


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

	/**
	 * データ挿入
	 * @param dto 挿入対象DTO
	 * @return 挿入結果(件数)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws MospException
	 */
	public int insert(MosPUserDto 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 更新結果(件数)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws MospException
	 */
	public int update(MosPUserDto dto, boolean needLog) throws SQLException, IllegalAccessException, NoSuchFieldException, MospException {
		try {
			index = 1;
			prepareStatement(getUpdateQuery(getClass()));
			setParams(dto, false);
			setParam(index++, dto.getUserId());
			executeUpdate(needLog);
			chkUpdate(1);
			return cnt;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}

	/**
	 * パラメータ設定
	 * @param dto      更新対象DTO
	 * @param isInsert 挿入文フラグ(true：挿入文、false：更新文)
	 * @throws SQLException
	 */
	private void setParams(MosPUserDto 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);
	}

	/**
	 * 社員コード検索用サブクエリー
	 * @return	sb	生成サブクエリ
	 */
	public static String getSearchKCodeSubQuery() {
		StringBuffer sb = new StringBuffer();
		sb.append(" SELECT ");
		sb.append(COL_K_CODE);
		sb.append(" FROM ");
		sb.append(TABLE);
		sb.append(" WHERE ");
		sb.append(COL_USER_ID);
		sb.append(" <> 'admin'");
		sb.append(" AND ");
		sb.append(COL_K_CODE);
		sb.append(" LIKE ? ");
		return sb.toString();
	}

	/**
	 * 社員名検索用サブクエリー
	 * @return	sb	生成サブクエリ
	 */
	public static String getSearchKNameSubQuery() {
		StringBuffer sb = new StringBuffer();
		sb.append(" SELECT ");
		sb.append(COL_K_CODE);
		sb.append(" FROM ");
		sb.append(TABLE);
		sb.append(" WHERE ");
		sb.append(COL_USER_ID);
		sb.append(" <> 'admin'");
		sb.append(" AND ");
		sb.append(COL_USER_NAME);
		sb.append(" LIKE ? ");
		return sb.toString();
	}

	/**
	 * 権限検索用サブクエリー
	 * @return	sb	生成サブクエリ
	 */
	public static String getSearchAuthoritySubQuery() {
		StringBuffer sb = new StringBuffer();
		sb.append(" SELECT ");
		sb.append(COL_K_CODE);
		sb.append(" FROM ");
		sb.append(TABLE);
		sb.append(" WHERE ");
		sb.append(COL_USER_ID);
		sb.append(" <> 'admin'");
		sb.append(" AND ");
		sb.append(COL_AUTHORITY);
		sb.append(" = ? ");
		return sb.toString();
	}

	/**
	 * 承認権限検索用サブクエリー
	 * @return	sb	生成サブクエリ
	 */
	public static String getSearchApprovalSubQuery() {
		StringBuffer sb = new StringBuffer();
		sb.append(" SELECT ");
		sb.append(COL_K_CODE);
		sb.append(" FROM ");
		sb.append(TABLE);
		sb.append(" WHERE ");
		sb.append(COL_USER_ID);
		sb.append(" <> 'admin'");
		sb.append(" AND ");
		sb.append(" ( ");
		sb.append(		COL_AUTHORITY);
		sb.append(		" = ? ");
		sb.append(		" OR ");
		sb.append(		COL_AUTHORITY);
		sb.append(		" = ? ");
		sb.append(" ) ");
		return sb.toString();
	}

	/**
	 * 社員コード検索用サブクエリー
	 * @return	sb	生成サブクエリ
	 */
	public static String getSearchDataLevelSubQuery() {
		StringBuffer sb = new StringBuffer();
		sb.append(" SELECT ");
		sb.append(COL_K_CODE);
		sb.append(" FROM ");
		sb.append(TABLE);
		sb.append(" WHERE ");
		sb.append(COL_USER_ID);
		sb.append(" <> 'admin'");
		sb.append(" AND ");
		sb.append(COL_DATA_LEVEL);
		sb.append(" <= ? ");
		return sb.toString();
	}

}
