/*
 * 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.system.action;

import java.io.Serializable;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import jp.mosp.common.CommonConst;
import jp.mosp.common.action.MosPAction;
import jp.mosp.common.common.MospConst;
import jp.mosp.common.common.MospException;
import jp.mosp.common.common.MospUtility;
import jp.mosp.common.dao.MosPUserDao;
import jp.mosp.common.dto.MosPUserDto;
import jp.mosp.system.vo.AccountMasterListVo;

public class AccountMasterListAction extends MosPAction {

	// コマンド
	private static final String CMD_ACCOUNT_MASTER_LIST_SHOW      = "S2400";
	private static final String CMD_ACCOUNT_MASTER_LIST_SEARCH    = "S2401";
	public  static final String CMD_ACCOUNT_MASTER_LIST_RE_SEARCH = "S2402";
	private static final String CMD_ACCOUNT_MASTER_LIST_SORT      = "S2403";
	private static final String CMD_ACCOUNT_MASTER_LIST_PASS_INIT = "S2404";

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

	/**
	 * アクション
	 */
	public void action() throws Exception {
		// DBコネクション取得
		getConnection();
		// SYSTEM権限確認
		confirmSystemAuth();
		// VOの取得
		AccountMasterListVo vo;
		Object obj = session.getAttribute(MospConst.ATT_FORMER_VO);
		if (obj instanceof AccountMasterListVo) {
			vo = (AccountMasterListVo)obj;
			vo.clearMessage();
			vo.clearErrField();
		} else {
			vo = new AccountMasterListVo();
		}
		vo.clearMessage();
		vo.clearErrField();
		vo.initVo(cfg, msg, cmd, aspUser, user);
		// VO及びフォワード先URLの設定
		setVo(vo);
		setUrl(vo.getRetUrl());
		session.setAttribute(MospConst.ATT_FORMER_VO, vo);
		// モード設定
		setMode(vo);
		// コマンド毎の処理
		if (cmd.equals(CMD_ACCOUNT_MASTER_LIST_SHOW)) {
			// 表示
			getConnection();
			vo.setPltDelete(MospConst.DELETE_FLAG_OFF);
			/*						
			 *  	2009/01/09	k.taniai	メニューアレンジ対応
			 */
			vo.aryPltAuthority = util.combineArray(getCodeArray(CommonConst.TID_AUTHORITY), getArrangeAuthArray());
		} else if (cmd.equals(CMD_ACCOUNT_MASTER_LIST_SEARCH)) {
			// 検索
			vo.setParams(request);
			searchUserList(vo);
			vo.setFormerKey(vo.KEY_USER_ID);
			vo.setIsAscending(true);
			vo.initListInfo();
		} else if (cmd.equals(CMD_ACCOUNT_MASTER_LIST_RE_SEARCH)) {
			// 再検索
			session.removeAttribute(MospConst.ATT_DTO);
			searchUserList(vo);
			vo.setPageButton();
			sortList(vo);
		} else if (cmd.equals(CMD_ACCOUNT_MASTER_LIST_SORT)) {
			// ソート
			sortList(key1, vo);
		} else if (cmd.equals(CMD_ACCOUNT_MASTER_LIST_PASS_INIT)) {
			// パスワード初期化
			initPassword(vo, key1);
		} else {
			throw new MospException(MospConst.EX_CMD_INVALID);
		}
	}

	/**
	 * ユーザーリスト検索
	 * @param vo UserListVoインスタンス
	 * @throws Exception
	 */
	private void searchUserList(AccountMasterListVo vo) throws Exception {
		// DBコネクションの取得
		getConnection();
		// 検索
		MosPUserDao dao = new MosPUserDao();
		dao.initDao(cfg, cmd, aspUser, user, conn);
		vo.setFields(dao.findForCondition(vo.getTxtUserId(), vo.getTxtUserName(), vo.getPltAuthority(), vo.getPltDelete()));
		// 対象が無かった場合のメッセージ設定
		if (vo.getEscAryUserId().length == 0) {
			vo.addErrMessage(MospUtility.getMessage(msg, MospConst.MSG_NO_DATA, ""));
		}
	}

	/**
	 * パスワード初期化
	 * @param vo     UserListVoインスタンス
	 * @param userId 対象ユーザーID
	 * @throws Exception
	 */
	private void initPassword(AccountMasterListVo vo, String userId) throws Exception {
		// DBコネクションの取得
		if (conn == null) {
			getConnection();
		}
		// 初期化準備
		MosPUserDao dao = new MosPUserDao();
		dao.initDao(cfg, cmd, aspUser, user, conn);
		// データの準備
		MosPUserDto dto = dao.findForUpdate(userId);
		// 存在確認
		chkExist(dto);
		// 値の設定
		dto.setPassword(MospUtility.getDigest(MospUtility.getDigest(userId)));
		// データの更新
		dao.update(dto, false);
		// コミット
		commit();
		// メッセージ設定
		vo.setMessage(MospUtility.getMessage(msg, MospConst.MSG_UPDATE, ""));
	}

	/**
	 * モード設定
	 * @param vo
	 * @throws Exception
	 */
	private void setMode(AccountMasterListVo vo) throws Exception{
		// DBコネクションの取得
		if (conn == null) {
			getConnection();
		}
		// 初期化準備
		MosPUserDao dao = new MosPUserDao();
		dao.initDao(cfg, cmd, aspUser, user, conn);
		List<MosPUserDto> listHuman = dao.findAllMosPUser();
		// HUMAN権限確認
		boolean hasAuth = false;
		String[][] aryHuman = getConfArray(CommonConst.CONF_ID_HUMAN);
		for (Iterator iter = listHuman.iterator(); iter.hasNext();) {
			MosPUserDto dto = (MosPUserDto) iter.next();
			for (int i = 0; i < aryHuman.length; i++) {
				if (aryHuman[i][0].equals(dto.getAuthority())) {
					hasAuth = true;
					break;
				}
			}
		}
		if (hasAuth) {		
			vo.setMode(AccountMasterListVo.MODE_VIEW);
		} else {
			vo.setMode(AccountMasterListVo.MODE_INSERT);
		}		
	}

	/**
	 * ソート
	 * @param key ソートキー
	 * @param vo ソート対象Listを含むVO
	 * @throws MospException
	 */
	private void sortList(String key, AccountMasterListVo vo) throws MospException {
		vo.sortList(key, getComparator(key, vo));
		vo.setFields(vo.getList());
	}

	/**
	 * ソート(VO内のキー情報でソート)
	 * @param vo ソート対象Listを含むVO
	 * @throws MospException
	 */
	private void sortList(AccountMasterListVo vo) throws MospException {
		vo.sortList(getComparator(vo.getFormerKey(), vo));
		vo.setFields(vo.getList());
	}

	/**
	 * 比較クラス取得
	 * @param key ソートキー
	 * @param vo ソート対象Listを含むVO
	 * @throws MospException
	 */
	private Comparator getComparator(String key, AccountMasterListVo vo) throws MospException {
		Comparator comp = null;
		if (key.equals(vo.KEY_USER_ID)) {
			comp = new CompUserId();
		} else if (key.equals(vo.KEY_USER_NAME)) {
			comp = new CompUserName();
		} else if (key.equals(vo.KEY_AUTHORITY)) {
			comp = new CompMospAuthority();
		} else if (key.equals(vo.KEY_DELETE)) {
			comp = new CompDeleteFlag();
		} else {
			throw new MospException(MospConst.EX_SORTKEY_INVALID);
		}
		return comp;
	}

	/**
	 * ユーザーIDによる比較クラス
	 */
	protected static class CompUserId implements Comparator, Serializable {
		private static final long serialVersionUID = -4583472093732229895L;
		public int compare(Object obj1, Object obj2) {
			MosPUserDto dto1 = (MosPUserDto)obj1;
			MosPUserDto dto2 = (MosPUserDto)obj2;
			return dto1.getUserId().compareTo(dto2.getUserId());
		}
	}

	/**
	 * ユーザー名による比較クラス
	 */
	protected static class CompUserName implements Comparator, Serializable {
		private static final long serialVersionUID = -8592798017682994795L;
		public int compare(Object obj1, Object obj2) {
			MosPUserDto dto1 = (MosPUserDto)obj1;
			MosPUserDto dto2 = (MosPUserDto)obj2;
			return dto1.getUserName().compareTo(dto2.getUserName());
		}
	}

	/**
	 * MosP利用権限による比較クラス
	 */
	protected static class CompMospAuthority implements Comparator, Serializable {
		private static final long serialVersionUID = -5352768820840940232L;

		public int compare(Object obj1, Object obj2) {
			MosPUserDto dto1 = (MosPUserDto)obj1;
			MosPUserDto dto2 = (MosPUserDto)obj2;
			return dto1.getAuthority().compareTo(dto2.getAuthority());
		}
	}

	/**
	 * 削除フラグによる比較クラス
	 */
	protected static class CompDeleteFlag implements Comparator, Serializable {
		private static final long serialVersionUID = -6928899434272685923L;
		public int compare(Object obj1, Object obj2) {
			MosPUserDto dto1 = (MosPUserDto)obj1;
			MosPUserDto dto2 = (MosPUserDto)obj2;
			return dto2.getDeleteFlag() - dto1.getDeleteFlag();
		}
	}

}
