/*

Copyright (C) 2009 NTT DATA INTELLILINK CORPORATION

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, version 2.

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.

 */

package jp.co.intellilink.hinemos.test.job;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;

import jp.co.intellilink.hinemos.test.util.Config;
import jp.co.intellilink.hinemos.test.util.EjbConnectionManager;
import jp.co.intellilink.hinemos.test.util.Messages;
import jp.co.intellilink.hinemos.test.util.StringListComparator;
import jp.co.intellilink.hinemos.test.util.WriteCsvFile;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.clustercontrol.bean.JobConstant;
import com.clustercontrol.bean.Property;
import com.clustercontrol.bean.ViewListInfo;
import com.clustercontrol.jobmanagement.bean.HistoryFilterPropertyConstant;
import com.clustercontrol.jobmanagement.bean.HistoryTableDefine;
import com.clustercontrol.jobmanagement.bean.JobInfo;
import com.clustercontrol.jobmanagement.bean.JobTreeItem;
import com.clustercontrol.jobmanagement.bean.ScheduleTableDefine;
import com.clustercontrol.jobmanagement.ejb.session.JobController;
import com.clustercontrol.util.PropertyUtil;

/**
 * ジョブ実行結果をチェックするクラス<br>
 * 
 * @version 1.1.0
 * @since 1.1.0
 */
public class CheckResultJob {
	private Date fromDate;

	// ログ出力
	private static Log log = LogFactory.getLog(CheckResultJob.class);

	public CheckResultJob(Date fromDate){
		this.fromDate = fromDate;
	}
	
	/**
	 * ジョブ実行結果をチェックする。<br>
	 */
	@SuppressWarnings("unchecked")
	public void checkResult() {
		log.info("[" + Messages.getMsg("CheckResult")+ "] " + Messages.getMsg("TestTool.Job.Start"));

		//ジョブツリー取得
		JobTreeItem jobTree = getJobTree();

		//ジョブ情報のCSV文字列を作成
		ArrayList<ArrayList<String>> csvOutput = new ArrayList<ArrayList<String>>();
		getJobData(jobTree, csvOutput);
		//ジョブIDでソート
		Collections.sort(csvOutput, new StringListComparator(0));

		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss");
		WriteCsvFile.writeCsvFile(
				Config.getConfig("Testcase.Output.Dir") + "/JOB_" + format.format(new Date()) + ".csv", 
				csvOutput);

		log.info("[" + Messages.getMsg("CheckResult")+ "] " + Messages.getMsg("TestTool.Job.End"));
	}

	/**
	 * ジョブ情報取得（再帰呼び出し）
	 * 
	 * @param treeItem ジョブツリー
	 * @param csvOutput CSV出力文字列配列
	 */
	public void getJobData(JobTreeItem treeItem, ArrayList<ArrayList<String>> csvOutput) {

		//子ツリーを取得する
		if (treeItem.getData() instanceof JobInfo){
			JobInfo info = treeItem.getData();
			if(info.getId() != null && info.getId().compareTo("") != 0){
				Object[] args = {info.getId()};
				log.info(Messages.getMsg("TestTool.JobID", args));

				ArrayList<String> csvFormat = createCsvFormat(info);
				String parentJobId = "";
				if(treeItem.getParent() != null){
					if (treeItem.getParent().getData() instanceof JobInfo){
						JobInfo parentInfo = treeItem.getParent().getData();
						if(parentInfo.getId() != null && parentInfo.getId().compareTo("") != 0){
							parentJobId = parentInfo.getId();
						}
					}
				}
				csvFormat.add(4, parentJobId);
				csvOutput.add(csvFormat);
			}
		}


		JobTreeItem[] childrenTreeItem = treeItem.getChildren();
		for (JobTreeItem childTreeItem : childrenTreeItem) {
			getJobData(childTreeItem, csvOutput);
		}
	}

	/**
	 * ジョブ情報からCSV文字列を作成する。<br>
	 * 
	 * @param info ジョブ情報
	 * @return CSVフォーマット文字列
	 */
	@SuppressWarnings("unchecked")
	public ArrayList<String> createCsvFormat(JobInfo info) {
		ArrayList<String> csvFormat = new ArrayList<String>();

		//ジョブID
		csvFormat.add(info.getId());
		//ジョブ名
		csvFormat.add(info.getName());
		//ジョブ種別
		csvFormat.add(JobConstant.typeToString(info.getType()));

		ViewListInfo viewListInfo = getSessionList(info.getId());
		if(viewListInfo.getList() instanceof ArrayList){
			Iterator itr = viewListInfo.getList().iterator();
			while(itr.hasNext()){
				ArrayList line = (ArrayList)itr.next();
				String ｓtartTime = "";
				String EndTime = "";
				if(line.get(HistoryTableDefine.SCHEDULED_START_TIME) instanceof Date){
					Date time = (Date)line.get(HistoryTableDefine.SCHEDULED_START_TIME);
					ｓtartTime = DateFormat.getDateTimeInstance().format(time);
				}
				if(line.get(HistoryTableDefine.END_SUSPEND_TIME) instanceof Date){
					Date time = (Date)line.get(HistoryTableDefine.END_SUSPEND_TIME);
					EndTime = DateFormat.getDateTimeInstance().format(time);
				}

				//開始日時
				csvFormat.add(ｓtartTime);

				//終了日時
				csvFormat.add(EndTime);

				break;
			}
		}
		
		csvFormat.add("");
		csvFormat.add("");
		csvFormat.add("");

		return csvFormat;
	}
	
	/**
	 * ジョブセッション一覧を取得する。<br>
	 * 
	 * @return ジョブセッション一覧
	 */
	protected ViewListInfo getSessionList(String jobId) {

		JobController job = EjbConnectionManager.getConnectionManager().getJobController();

		ViewListInfo info = null;
		try {
			@SuppressWarnings("unchecked")
			ArrayList properties = null;
			Property filter = job.getHistoryFilterProperty(Locale.getDefault());

			//ジョブIDを設定
			if(jobId instanceof String){
				properties = PropertyUtil.getProperty(filter, HistoryFilterPropertyConstant.JOB_ID);
				((Property)properties.get(0)).setValue(jobId);
			}

			//開始・再実行日時（開始）を設定
			if(fromDate instanceof Date){
				properties = PropertyUtil.getProperty(filter, HistoryFilterPropertyConstant.START_FROM_DATE);
				((Property)properties.get(0)).setValue(fromDate);
			}

			int maxlist = Integer.parseInt(Config.getConfig("history.job.max.list"));

			info = job.getHistoryList(filter, maxlist);
		} catch (Exception e) {
			log.error(Messages.getMsg("TestTool.ConnectManagerFailed"), e);
			System.exit(14);
		}
		return info;
	}

	/**
	 * ジョブツリーを取得する。<br>
	 * 
	 * @return ジョブツリー
	 */
	protected JobTreeItem getJobTree() {

		JobController job = EjbConnectionManager.getConnectionManager().getJobController();

		JobTreeItem jobTree = null;
		try {
			jobTree = job.getJobTree(true, Locale.getDefault());
		} catch (Exception e) {
			log.error(Messages.getMsg("TestTool.ConnectManagerFailed"), e);
			System.exit(14);
		}
		return jobTree;
	}
}