/*
 * MosP - Mind Open Source Project         http://www.mosp.jp/
 * Copyright (C) 1987-2009 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.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import jp.mosp.common.common.MospException;
import jp.mosp.common.dto.CmAspUserDto;
import jp.mosp.common.dto.CmUserDto;

public class MosPUserDao extends CmUserDao {

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

	/**
	 * コンストラクタ。<br>
	 * @param cfg     設定ファイル
	 * @param cmd     コマンド
	 * @param aspUser ASPユーザー
	 * @param user    ユーザー
	 * @param conn    DBコネクション
	 */
	public MosPUserDao(
			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	検索結果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;
	}

	/**
	 * 全データ取得
	 * @return 検索結果(DTOのList)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 */
	public List<CmUserDto> findAllMosPUser() throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			prepareStatement(getSelectQuery(getClass()) + getOrderForKey(getClass()));
			executeQuery();
			List<CmUserDto> allMosPUser = mappingAll();
			return allMosPUser;
		} 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 CmUserDto 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();
			CmUserDto dto = null;
			if (rs.next()) {
				dto = mapping();
			}
			return dto;
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}


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

	/**
	 * データ更新
	 * @param dto 更新対象DTO
	 * @return 更新結果(件数)
	 * @throws SQLException
	 * @throws IllegalAccessException
	 * @throws NoSuchFieldException
	 * @throws MospException
	 */
	public int update(CmUserDto 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(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);
	}

	/**
	 * 社員コード検索用サブクエリー
	 * @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();
	}

}
