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

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

import jp.mosp.common.action.MosPWorkflowAction;
import jp.mosp.common.common.MospConst;
import jp.mosp.common.common.MospException;
import jp.mosp.common.common.MospUtility;


import jp.mosp.workflow.dto.AmRouteDto;
import jp.mosp.workflow.dto.AmUnitDto;
import jp.mosp.workflow.vo.ApprovalRouteListVo;

public class ApprovalRouteListAction extends MosPWorkflowAction {

	// コマンド
	private static final String CMD_ROUTE_LIST_SHOW      = "S2820";
	private static final String CMD_ROUTE_LIST_SEARCH    = "S2821";
	private static final String CMD_ROUTE_LIST_RE_SEARCH = "S2822";
	private static final String CMD_ROUTE_LIST_SORT      = "S2823";

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

	/**
	 * アクション
	 */
	public void action() throws Exception {
		// DBコネクション取得
		getConnection();
		// SYSTEM権限確認
		confirmSystemAuth();
		// VOの取得
		ApprovalRouteListVo vo;
		Object obj = session.getAttribute(MospConst.ATT_FORMER_VO);
		if (obj instanceof ApprovalRouteListVo) {
			vo = (ApprovalRouteListVo)obj;
		} else {
			vo = new ApprovalRouteListVo();
		}
		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);
		// ユニット情報取得
		vo.aryPltUnit = getCurrentUnitArrayForList();
		// コマンド毎の処理
		if (cmd.equals(CMD_ROUTE_LIST_SHOW)) {
			// 検索履歴を初期値にセット
			vo.setSearchmode(ApprovalRouteListVo.SEARCH_OFF);
		} else if (cmd.equals(CMD_ROUTE_LIST_SEARCH)) {
			// 検索
			vo.setParams(request);
			searchRouteList(vo);
			vo.setFormerKey(vo.KEY_ROUTE_CODE);
			vo.setIsAscending(true);
			vo.initListInfo();
		} else if (cmd.equals(CMD_ROUTE_LIST_RE_SEARCH)) {
			// 再検索
			if (vo.getSearchmode() == ApprovalRouteListVo.SEARCH_ON) {
				session.removeAttribute(MospConst.ATT_DTO);
				searchRouteList(vo);
				vo.setPageButton();
				sortList(vo);
			}
		} else if (cmd.equals(CMD_ROUTE_LIST_SORT)) {
			// ソート
			sortList(key1, vo);
		} else {
			throw new MospException(MospConst.EX_CMD_INVALID);
		}
	}

	/**
	 * ルートリスト検索
	 * @param vo UserListVoインスタンス
	 * @throws Exception
	 */
	private void searchRouteList(ApprovalRouteListVo vo) throws Exception {
		// DBコネクションの取得
		if (conn == null) {
			getConnection();
		}
		// 検索
		vo.setFields(routeDao().findForCondition(
				vo.getTxtRouteCode(),
				vo.getTxtUnitCode(),
				vo.getTxtKCode(),
				vo.getTxtKName())
		);
		// 対象が無かった場合のメッセージ設定
		if (vo.getEscAryRoute().length == 0) {
			vo.addErrMessage(MospUtility.getMessage(msg, MospConst.MSG_NO_DATA, ""));
		}
		vo.setSearchmode(ApprovalRouteListVo.SEARCH_ON);
	}

	/**
	 * 現状承認ユニットコード一覧（AM_UNIT）
	 * @return　現状の承認ユニットコードリスト
	 * @throws Exception
	 */
	protected String[][] getCurrentUnitArrayForList() throws Exception {
		String targetDate = util.convDateFormattedByHyphen(util.getSystemDate());
		// 情報の取得
		List<AmUnitDto> listUnit = unitDao().findForCurrentUnitArray(targetDate);
		// 配列の作成		
		String[][] aryUnitList = new String[listUnit.size()][2];
		for (int i = 0; i < listUnit.size(); i++) {
			aryUnitList[i][0] = listUnit.get(i).getUnitCode();
			aryUnitList[i][1] = getKName(listUnit.get(i).getMain());
		}
		return aryUnitList;
	}

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

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

	/**
	 * 比較クラス取得
	 * @param key ソートキー
	 * @param vo ソート対象Listを含むVO
	 * @throws MospException
	 */
	private Comparator<Object> getComparator(String key, ApprovalRouteListVo vo) throws MospException {
		Comparator<Object> comp = null;
		if (key.equals(vo.KEY_ROUTE_CODE)) {
			comp = new CompRouteCode();
		} else {
			throw new MospException(MospConst.EX_SORTKEY_INVALID);
		}
		return comp;
	}

	/**
	 * ユニットコードによる比較クラス
	 */
	protected static class CompRouteCode implements Comparator<Object>, Serializable {
		private static final long serialVersionUID = 7410652204380257012L;
		public int compare(Object obj1, Object obj2) {
			AmRouteDto dto1 = (AmRouteDto)obj1;
			AmRouteDto dto2 = (AmRouteDto)obj2;
			return dto1.getRtCode().compareTo(dto2.getRtCode());
		}
	}

}
