/*

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.export.history;

import java.rmi.RemoteException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Locale;

import javax.ejb.CreateException;
import javax.ejb.FinderException;
import javax.naming.NamingException;

import jp.co.intellilink.hinemos.util.CheckString;
import jp.co.intellilink.hinemos.util.Config;
import jp.co.intellilink.hinemos.util.DateListComparator;
import jp.co.intellilink.hinemos.util.EjbConnectionManager;
import jp.co.intellilink.hinemos.util.Messages;
import jp.co.intellilink.hinemos.util.WriteCsvFile;

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

import com.clustercontrol.bean.Property;
import com.clustercontrol.monitor.bean.EventFilterConstant;
import com.clustercontrol.monitor.bean.ReportEventInfo;
import com.clustercontrol.monitor.ejb.session.MonitorController;
import com.clustercontrol.util.PropertyUtil;

/**
 * イベントをCSV出力するクラス<br>
 * 
 * @version 1.0.0
 * @since 1.0.0
 */
public class ExportEvent {

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

	/**
	 * イベントをCSV出力する。<br>
	 * 
	 * @param startDate 開始日時
	 */
	public void export(Date startDate) {
		log.info(Messages.getMsg("ExportTool.Event.Start"));

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

		Calendar cal = Calendar.getInstance();
		cal.setTime(startDate);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		Date startTime = cal.getTime();

		cal.add(Calendar.DATE, 1);
		cal.add(Calendar.MILLISECOND, -1);
		Date endTime = cal.getTime();

		ArrayList<ReportEventInfo> events = getEvent(startTime, endTime);

		for(ReportEventInfo event : events){
			csvOutput.addAll(createEvent(event));
		}

		//受信日時でソート
		Collections.sort(csvOutput, new DateListComparator(1));

		csvOutput.add(0, createHeader());

		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

		WriteCsvFile.writeCsvFile(
				Config.getConfig("History.Dir") + "/EVENT_" + format.format(startTime) + ".csv", 
				csvOutput);

		log.info(Messages.getMsg("ExportTool.Event.End"));
	}

	/**
	 * CSVフォーマットのヘッダ文字列を作成する。<br>
	 * 
	 * @return CSVフォーマット文字列
	 */
	public ArrayList<String> createHeader() {
		ArrayList<String> csvFormat = new ArrayList<String>();

		csvFormat.add(com.clustercontrol.util.Messages.getString("priority"));
		csvFormat.add(com.clustercontrol.util.Messages.getString("receive.time"));
		csvFormat.add(com.clustercontrol.util.Messages.getString("output.time"));
		csvFormat.add(com.clustercontrol.util.Messages.getString("plugin.id"));
		csvFormat.add(com.clustercontrol.util.Messages.getString("monitor.id"));
		csvFormat.add(com.clustercontrol.util.Messages.getString("facility.id"));
		csvFormat.add(com.clustercontrol.util.Messages.getString("scope"));
		csvFormat.add(com.clustercontrol.util.Messages.getString("application"));
		csvFormat.add(com.clustercontrol.util.Messages.getString("message.id"));
		csvFormat.add(com.clustercontrol.util.Messages.getString("message"));
		csvFormat.add(com.clustercontrol.util.Messages.getString("message.org"));
		csvFormat.add(com.clustercontrol.util.Messages.getString("confirmed"));
		csvFormat.add(com.clustercontrol.util.Messages.getString("confirm.user"));

		return csvFormat;
	}

	/**
	 * イベント情報からCSVフォーマット文字列を作成する。<br>
	 * 
	 * @param event イベント情報
	 * @return CSVフォーマット文字列
	 */
	public ArrayList<ArrayList<String>> createEvent(ReportEventInfo event) {
		ArrayList<ArrayList<String>> csvFormat = new ArrayList<ArrayList<String>>();
		ArrayList<String> csvLine = new ArrayList<String>();

		DateFormat format = DateFormat.getDateTimeInstance();

		//重要度
		csvLine.add(event.getPriority());
		//受信日時
		csvLine.add(format.format(event.getGenerationDate()));
		//出力日時
		csvLine.add(format.format(event.getOutputDate()));
		//プラグインID
		csvLine.add(event.getPluginId());
		//監視項目ID
		csvLine.add(event.getMonitorId());
		//ファシリティID
		csvLine.add(event.getFacilityId());
		//スコープ
		csvLine.add(event.getScopeText());
		//アプリケーション
		csvLine.add(event.getApplication());
		//メッセージID
		csvLine.add(event.getMessageId());
		//メッセージ
		csvLine.add(event.getMessage());
		//オリジナルメッセージ
		csvLine.add(CheckString.checkReturn(event.getMessageOrg()));
		//確認
		csvLine.add(event.getConfirmFlg());
		//確認ユーザ
		csvLine.add(event.getConfirmUser());

		csvFormat.add(csvLine);

		return csvFormat;
	}

	/**
	 * イベント情報を取得します。<br>
	 * 
	 * @param fromDate 出力日時（開始）
	 * @param toDate 出力日時（終了）
	 * @return イベント情報
	 */
	public ArrayList<ReportEventInfo> getEvent(
			Date fromDate, Date toDate) {

		MonitorController monitor = 
			EjbConnectionManager.getConnectionManager().getMonitorController();

		ArrayList<ReportEventInfo> records = null;
		try {
			Property filter = monitor.getEventFilterProperty(Locale.getDefault());

			//重要度を設定
			ArrayList properties = PropertyUtil.getProperty(filter, EventFilterConstant.PRIORITY);
			((Property)properties.get(0)).setValue("");

			//出力日時（開始）を設定
			if(fromDate instanceof Date){
				properties = PropertyUtil.getProperty(filter, EventFilterConstant.OUTPUT_FROM_DATE);
				((Property)properties.get(0)).setValue(fromDate);
			}

			//出力日時（終了）を設定
			if(toDate instanceof Date){
				properties = PropertyUtil.getProperty(filter, EventFilterConstant.OUTPUT_TO_DATE);
				((Property)properties.get(0)).setValue(toDate);
			}

			//確認を設定
			properties = PropertyUtil.getProperty(filter, EventFilterConstant.CONFIRMED);
			((Property)properties.get(0)).setValue("-1");

			records = monitor.getEventListForReport(null, filter);
		} catch (RemoteException e) {
		} catch (CreateException e) {
		} catch (FinderException e) {
		} catch (NamingException e) {
		}

		return records;
	}
}