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

/**
 * CM_USER(ユーザーマスタ)のDAOクラス 。
 */
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 SQL例外が発生した場合
	 */
	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 SQL例外が発生した場合
	 */
	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 SQL例外が発生した場合
	 * @throws IllegalAccessException	メソッドにアクセスできない場合
	 * @throws NoSuchFieldException	フィールドが見つからなかった場合
	 */
	public List<CmUserDto> findAllMosPUser() throws SQLException, IllegalAccessException, NoSuchFieldException {
		try {
			prepareStatement(getSelectQuery(getClass()) + getOrderForKey(getClass()));
			executeQuery();
			return mappingAll();
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * 条件文によるデータ取得
	 * @param userId 検索ユーザーID
	 * @param userName 検索ユーザー名
	 * @param mospAuthority 検索MosP利用権限
	 * @param deleteFlag 検索削除フラグ
	 * @return 検索結果(DTOのList)
	 * @throws SQLException SQL例外が発生した場合
	 * @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(notAdminUser());
		sb.append("AND ");
		sb.append(MosPDao.like(COL_USER_ID));
		sb.append("AND ");
		sb.append(MosPDao.like(COL_USER_NAME));*/
		this.pob.appendWhere(COL_USER_ID, Query.FilterOperator.NOT_EQUAL, "admin");
		this.pob.appendLike(COL_USER_ID);
		this.pob.appendLike(COL_USER_NAME);
		if (MosPDao.isNotNull(mospAuthority)) {
			sb.append("AND ");
//			sb.append(MosPDao.equal(COL_AUTHORITY));
			this.pob.appendWhere(COL_AUTHORITY, Query.FilterOperator.EQUAL);
		}
		if (MosPDao.isNotNull(deleteFlag)) {
			sb.append("AND ");
//			sb.append(MosPDao.equal(COL_DELETE_FLAG));
			this.pob.appendWhere(COL_DELETE_FLAG, Query.FilterOperator.EQUAL);
		}
		try {
			prepareStatement(getSelectQuery(getClass()) + sb.toString() + getOrderForKey(getClass()));
			setParam(index++, MosPDao.startWithParam(userId));
			setParam(index++, MosPDao.containsParam(userName));
			if (MosPDao.isNotNull(mospAuthority)) {
				setParam(index++, mospAuthority);
			}
			if (MosPDao.isNotNull(deleteFlag)) {
				setParam(index++, Integer.parseInt(deleteFlag));
			}
			executeQuery();
			return mappingAll();
		} catch (SQLException e) {
			throw e;
		} finally {
			releaseResultSet();
			releasePreparedStatement();
		}
	}
	
	/**
	 * キーによるデータ取得
	 * @param userId ユーザーID(検索キー)
	 * @return 検索結果(DTO)
	 * @throws SQLException SQL例外が発生した場合
	 * @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(MosPDao.like(COL_USER_ID));
			sb.append("AND ");
//			sb.append(MosPDao.deleteFlagOff(COL_DELETE_FLAG));
			this.pob.appendLike(COL_USER_ID);
			this.pob.appendWhere(COL_DELETE_FLAG, Query.FilterOperator.EQUAL, MospConst.DELETE_FLAG_OFF);
			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 SQL例外が発生した場合
	 * @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(MosPDao.equal(COL_K_CODE));
			sb.append("AND ");
//			sb.append(notAdminUser());
			this.pob.appendWhere(COL_K_CODE, Query.FilterOperator.EQUAL);
			this.pob.appendWhere(COL_USER_ID, Query.FilterOperator.NOT_EQUAL, "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
	 * @param needLog ログ出力要否
	 * @return 更新結果(件数)
	 * @throws SQLException SQL例外が発生した場合
	 * @throws IllegalAccessException	メソッドにアクセスできない場合
	 * @throws NoSuchFieldException	フィールドが見つからなかった場合
	 * @throws MospException	MosP例外処理が発生した場合
	 */
	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 SQL例外が発生した場合
	 */
	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	生成サブクエリ
	 */
	// GAE
//	public static String getSearchKCodeSubQuery() {
	public 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(notAdminUser());
		sb.append("AND ");
		sb.append(MosPDao.like(COL_K_CODE));
		return sb.toString();*/
		this.setPreparedStatement(PreparedStatement.Mode.SELECT);
		this.pob.appendWhere(COL_USER_ID, Query.FilterOperator.NOT_EQUAL, "admin");
		return null;
	}
	
	/**
	 * 社員名検索用サブクエリー
	 * @return	sb	生成サブクエリ
	 */
	// GAE
//	public static String getSearchKNameSubQuery() {
	public 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(notAdminUser());
		sb.append("AND ");
		sb.append(MosPDao.like(COL_USER_NAME));
		return sb.toString();*/
		this.setPreparedStatement(PreparedStatement.Mode.SELECT);
		this.pob.appendWhere(COL_USER_ID, Query.FilterOperator.NOT_EQUAL, "admin");
		this.pob.appendLike(COL_USER_NAME);
		return null;
	}
	
	/**
	 * 権限検索用サブクエリー
	 * @return	sb	生成サブクエリ
	 */
	// GAE
//	public static String getSearchAuthoritySubQuery() {
	public 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(notAdminUser());
		sb.append("AND ");
		sb.append(MosPDao.equal(COL_AUTHORITY));
		return sb.toString();*/
		this.setPreparedStatement(PreparedStatement.Mode.SELECT);
		this.pob.appendWhere(COL_USER_ID, Query.FilterOperator.NOT_EQUAL, "admin");
		this.pob.appendWhere(COL_AUTHORITY, Query.FilterOperator.EQUAL);
		return null;
	}
	
	/**
	 * 承認権限検索用サブクエリー
	 * @return	sb	生成サブクエリ
	 */
	public static String getSearchApprovalSubQuery() {
		throw new CloudzeroUnsupportedException("OR文");
/*		StringBuffer sb = new StringBuffer();
		sb.append(" SELECT ");
		sb.append(COL_K_CODE);
		sb.append(" FROM ");
		sb.append(TABLE);
		sb.append(" WHERE ");
		sb.append(notAdminUser());
		sb.append("AND ");
		sb.append("(");
		sb.append(MosPDao.equal(COL_AUTHORITY));
		sb.append("OR ");
		sb.append(MosPDao.equal(COL_AUTHORITY));
		sb.append(") ");
		return sb.toString();*/
	}
	
	/**
	 * 社員コード検索用サブクエリー
	 * @return	sb	生成サブクエリ
	 */
//	public static String getSearchDataLevelSubQuery() {
	public 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(notAdminUser());
		sb.append("AND ");
		sb.append(COL_DATA_LEVEL);
		sb.append(" <= ? ");
		return sb.toString();*/
		this.setPreparedStatement(PreparedStatement.Mode.SELECT);
		this.pob.appendWhere(COL_USER_ID, Query.FilterOperator.NOT_EQUAL, "admin");
		this.pob.appendWhere(COL_DATA_LEVEL, Query.FilterOperator.LESS_THAN_OR_EQUAL);
		return null;
	}
	
	/**
	 * adminユーザを除くサブクエリ
	 * @return {@link CmUserDao#COL_USER_ID} <> 'admin'
	 */
	// GAE
/*	public static String notAdminUser() {
		StringBuffer sb = new StringBuffer();
		sb.append(COL_USER_ID);
		sb.append(" <> 'admin' ");
		return sb.toString();
	}*/
	
}
