/*

Copyright (C) 2008 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.maintenance;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;

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.YesNoConstant;
import com.clustercontrol.maintenance.bean.MaintenanceInfoDataImp;
import com.clustercontrol.maintenance.ejb.session.MaintenanceController;
import com.clustercontrol.notify.bean.NotifyRelationInfo;
import com.clustercontrol.notify.bean.NotifyTypeConstant;

/**
 * メンテナンス情報を基に試験項目のCSVフォーマット文字列を作成するクラス<br>
 * 
 * @version 1.0.0
 * @since 1.0.0
 */
public class ExportTestCaseMaintenamce {

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

	/**
	 * メンテナンス情報を基に試験項目のCSVフォーマット文字列を作成する。<br>
	 */
	public void exportTestCase() {
		log.info("[" + Messages.getMsg("ExportTestCase")+ "] " + Messages.getMsg("TestTool.Maintenance.Start"));

		//CSV出力配列を用意
		ArrayList<ArrayList<String>> csvOutput = new ArrayList<ArrayList<String>>();

		//メンテナンスIDリスト取得
		ArrayList idList = getMaintenanceIdList();

		if(idList instanceof ArrayList){
			Iterator itr = idList.iterator();
			while(itr.hasNext()){
				ArrayList line = (ArrayList)itr.next();

				Object[] args = {(String)line.get(0)};
				log.info("[" + Messages.getMsg("ExportTestCase")+ "] " + Messages.getMsg("TestTool.MaintenanceID", args));

				MaintenanceInfoDataImp info = getMaintenance((String)line.get(0));
				csvOutput.addAll(createTestCase(info));
			}

			//メンテナンスIDでソート
			Collections.sort(csvOutput, new StringListComparator(0));
		}

		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss");

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

		log.info("[" + Messages.getMsg("ExportTestCase")+ "] " + Messages.getMsg("TestTool.Maintenance.End"));
	}

	/**
	 * メンテナンス情報を基に試験項目のCSVフォーマット文字列を作成する。<br>
	 * 
	 * @param maintenanceInfo メンテナンス情報
	 * @return CSVフォーマット文字列
	 */
	public ArrayList<ArrayList<String>> createTestCase(MaintenanceInfoDataImp maintenanceInfo) {
		ArrayList<ArrayList<String>> csvFormat = new ArrayList<ArrayList<String>>();

		ArrayList<String> csvLine = new ArrayList<String>();
		//メンテナンスID
		csvLine.add(maintenanceInfo.getMaintenance_id());

		//ステータスチェック
		csvLine.addAll(checkStatus(maintenanceInfo));

		//イベントチェック（重要度別）
		csvLine.addAll(checkEvent(maintenanceInfo));

		//抑制チェック
		csvLine.addAll(checkNotify(maintenanceInfo));

		csvFormat.add(csvLine);

		return csvFormat;
	}

	/**
	 * ステータス通知の試験項目のCSVフォーマット文字列を作成する。<br>
	 * 
	 * @param maintenanceInfo メンテナンス情報
	 * @return CSVフォーマット文字列
	 */
	protected ArrayList<String> checkStatus(MaintenanceInfoDataImp maintenanceInfo) {
		ArrayList<String> csvFormat = new ArrayList<String>();

		String result = "-";

		//監視が有効の場合
		if(maintenanceInfo.getValid_flg() == YesNoConstant.TYPE_YES){
			String notifyId = null;
			if(maintenanceInfo.getNotifyId() != null){
				Collection<NotifyRelationInfo> notify = maintenanceInfo.getNotifyId();

				NotifyRelationInfo relationInfo;
				for (int i = 0; i < notify.size(); i++) {
					relationInfo = (NotifyRelationInfo)((ArrayList<NotifyRelationInfo>)notify).get(i);
					if(relationInfo.getNotifyType() == NotifyTypeConstant.TYPE_STATUS){
						notifyId = relationInfo.getNotifyId();
						break;
					}
				}
			}

			if(notifyId != null){
				result = "";
			}
		}

		csvFormat.add(result);

		return csvFormat;
	}

	/**
	 * イベント出力結果をチェックする。<br>
	 * 
	 * @param maintenanceInfo メンテナンス情報
	 * @return CSVフォーマット文字列
	 */
	protected ArrayList<String> checkEvent(MaintenanceInfoDataImp maintenanceInfo) {
		ArrayList<String> csvFormat = new ArrayList<String>();

		String info = "-";
		String warning = "-";
		String critical = "-";
		String unknown = "-";

		//監視が有効の場合
		if(maintenanceInfo.getValid_flg() == YesNoConstant.TYPE_YES){
			String notifyId = null;
			if(maintenanceInfo.getNotifyId() != null){
				Collection<NotifyRelationInfo> notify = maintenanceInfo.getNotifyId();

				NotifyRelationInfo relationInfo;
				for (int i = 0; i < notify.size(); i++) {
					relationInfo = (NotifyRelationInfo)((ArrayList<NotifyRelationInfo>)notify).get(i);
					if(relationInfo.getNotifyType() == NotifyTypeConstant.TYPE_EVENT){
						notifyId = relationInfo.getNotifyId();
						break;
					}
				}
			}

			if(notifyId != null){
				info = "";
				warning = "";
				critical = "";
				unknown = "";
			}
		}

		csvFormat.add(info);
		csvFormat.add(warning);
		csvFormat.add(critical);
		csvFormat.add(unknown);

		return csvFormat;
	}

	/**
	 * 通知抑制の結果をチェックする。<br>
	 * 
	 * @param maintenanceInfo メンテナンス情報
	 * @return CSVフォーマット文字列
	 */
	protected ArrayList<String> checkNotify(MaintenanceInfoDataImp maintenanceInfo) {
		ArrayList<String> csvFormat = new ArrayList<String>();

		String status = "-";
		String event = "-";
		String mail = "-";
		String job = "-";
		String syslog = "-";

		//監視が有効の場合
		if(maintenanceInfo.getValid_flg() == YesNoConstant.TYPE_YES){
			if(maintenanceInfo.getNotifyId() != null){
				Collection<NotifyRelationInfo> notify = maintenanceInfo.getNotifyId();

				NotifyRelationInfo relationInfo;
				for (int i = 0; i < notify.size(); i++) {
					relationInfo = (NotifyRelationInfo)((ArrayList<NotifyRelationInfo>)notify).get(i);
					if(relationInfo.getNotifyType() == NotifyTypeConstant.TYPE_STATUS)
						status = "";
					else if(relationInfo.getNotifyType() == NotifyTypeConstant.TYPE_EVENT)
						event = "";
					else if(relationInfo.getNotifyType() == NotifyTypeConstant.TYPE_MAIL)
						mail = "";
					else if(relationInfo.getNotifyType() == NotifyTypeConstant.TYPE_JOB)
						job = "";
					else if(relationInfo.getNotifyType() == NotifyTypeConstant.TYPE_LOG_ESCALATE)
						syslog = "";
				}
			}
		}

		csvFormat.add(status);
		csvFormat.add(event);
		csvFormat.add(mail);
		csvFormat.add(job);
		csvFormat.add(syslog);

		return csvFormat;
	}

	/**
	 * メンテナンス情報を取得する。<br>
	 * 
	 * @param maintenanceId 取得対象のメンテナンスID
	 * @return メンテナンス情報
	 */
	protected MaintenanceInfoDataImp getMaintenance(String maintenanceId) {

		MaintenanceController maintenance = EjbConnectionManager.getConnectionManager().getMaintenanceController();

		MaintenanceInfoDataImp info = null;
		try {
			info = maintenance.getMaintenanceInfo(maintenanceId);
		} catch (Exception e) {
			log.error("[" + Messages.getMsg("ExportTestCase")+ "] " + Messages.getMsg("TestTool.ConnectManagerFailed"), e);
			System.exit(14);
		}
		return info;
	}

	/**
	 * スケジュール情報を取得する。<br>
	 * 
	 * @param maintenanceId 取得対象のメンテナンスID
	 * @return スケジュール情報
	 */
	protected ArrayList getSchedule(String maintenanceId) {

		MaintenanceController maintenance = EjbConnectionManager.getConnectionManager().getMaintenanceController();

		ArrayList info = null;
		try {
			info = maintenance.getSchedule(maintenanceId);
		} catch (Exception e) {
			log.error("[" + Messages.getMsg("ExportTestCase")+ "] " + Messages.getMsg("TestTool.ConnectManagerFailed"), e);
			System.exit(14);
		}
		return info;
	}

	/**
	 * メンテナンスIDリストを取得する。<br>
	 * 
	 * @return メンテナンスID一覧
	 */
	protected ArrayList getMaintenanceIdList() {

		MaintenanceController maintenance = EjbConnectionManager.getConnectionManager().getMaintenanceController();

		ArrayList records = null;
		try {
			records = maintenance.getMaintenanceList();
		} catch (Exception e) {
			log.error("[" + Messages.getMsg("ExportTestCase")+ "] " + Messages.getMsg("TestTool.ConnectManagerFailed"), e);
			System.exit(14);
		}
		return records;
	}
}