/*

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.conf.monitor;

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

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

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

import com.clustercontrol.bean.PriorityConstant;
import com.clustercontrol.bean.ValidConstant;
import com.clustercontrol.monitor.run.bean.MonitorInfo;
import com.clustercontrol.monitor.run.bean.MonitorNumericValueInfo;
import com.clustercontrol.monitor.run.bean.MonitorTypeConstant;
import com.clustercontrol.sql.bean.SqlCheckInfo;
import com.clustercontrol.sql.ejb.session.MonitorSqlController;

/**
 * SQL監視情報を取得するクラス<br>
 * 
 * @version 1.0.0
 * @since 1.0.0
 */
public class ExportMonitorSql extends ExportMonitorNumeric {

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

	private List<List<String>> driverList = JdbcDriverUtil.getJdbcDriver();

	public ExportMonitorSql() {
		super(ExportMonitorNumeric.INPUT_VERIFICATION_INTEGER_NUMBER);
	}

	/**
	 * SQL監視情報をExportする。<br>
	 */
	public void exportSql() {
		log.info(Messages.getMsg("Sql.Start", new String[]{Messages.getMsg("ExportTool.Export")}));

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

		//監視項目リスト取得
		ArrayList idList = getSnmpList();

		if(idList instanceof ArrayList){
			Iterator itr = idList.iterator();
			while(itr.hasNext()){
				MonitorInfo info = (MonitorInfo)itr.next();
				if(info.getMonitorType() == MonitorTypeConstant.TYPE_NUMERIC){
					Object[] args = {info.getMonitorId()};
					log.info(Messages.getMsg("MonitorID", args));
					csvOutput.add(createCsvFormat(info));
				}
			}

			//監視項目IDでソート
			Collections.sort(csvOutput, new StringListComparator(0));
		}

		String timestamp = "";
		if(Config.getConfig("file.timestamp").equalsIgnoreCase("on")){
			SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss");
			timestamp = "_" + format.format(new Date());
		}
		WriteCsvFile.writeCsvFile(
				Config.getConfig("Export.Dir") + "/SQL" + timestamp + ".csv", 
				csvOutput);

		log.info(Messages.getMsg("Sql.End", new String[]{Messages.getMsg("ExportTool.Export")}));
	}

	/* (non-Javadoc)
	 * @see jp.co.intellilink.hinemos.export.monitor.ExportMonitorNumeric#createCsvFormat(com.clustercontrol.monitor.run.bean.MonitorInfo)
	 */
	@Override
	public ArrayList<String> createCsvFormat(MonitorInfo monitorInfo) {
		ArrayList<String> csvFormat = new ArrayList<String>();

		//監視基本情報
		csvFormat.addAll(createMonitorBase(monitorInfo));

		//監視条件情報
		csvFormat.addAll(createMonitorRule(monitorInfo));

		//監視情報
		csvFormat.addAll(createMonitorInfo(monitorInfo));

		//監視判定情報
		csvFormat.addAll(createMonitorJudgement(monitorInfo));

		//監視通知情報
		csvFormat.addAll(createMonitorNotify(monitorInfo));

		//アプリケーション
		if (monitorInfo.getApplication() != null)
			csvFormat.add(monitorInfo.getApplication());
		else
			csvFormat.add("");

		//メッセージ情報
		csvFormat.addAll(createMonitorMessage(monitorInfo));

		//有効/無効
		csvFormat.add(ValidConstant.typeToString(monitorInfo.getValid()));

		return csvFormat;
	}

	/**
	 * SQL監視情報をExportする。<br>
	 * 
	 * @param monitorInfo SQL監視情報
	 * @return CSVフォーマット文字列
	 */
	@Override
	public ArrayList<String> createMonitorInfo(MonitorInfo monitorInfo) {
		ArrayList<String> csvFormat = new ArrayList<String>();

		SqlCheckInfo sqlInfo = (SqlCheckInfo)monitorInfo.getSqlCheckInfo();
		if(sqlInfo == null){
			sqlInfo = new SqlCheckInfo();
		}
		//接続先URL
		if (sqlInfo.getConnectionUrl() != null)
			csvFormat.add(sqlInfo.getConnectionUrl());
		else
			csvFormat.add("");
		//接続先DB
		if (sqlInfo.getJdbcDriver() != null){
			for(int i = 0; i < driverList.size(); i++){
				List<String> driver = driverList.get(i);
				String className = (String)driver.get(1);
				if(className.equals(sqlInfo.getJdbcDriver())){
					csvFormat.add((String)driver.get(0));
					break;
				}
			}
		}
		else
			csvFormat.add("");
		//ユーザID
		if (sqlInfo.getUser() != null)
			csvFormat.add(sqlInfo.getUser().toString());
		else
			csvFormat.add("");
		//パスワード
		if (sqlInfo.getPassword() != null)
			csvFormat.add(sqlInfo.getPassword());
		else
			csvFormat.add("");
		//SQL
		if (sqlInfo.getQuery() != null)
			csvFormat.add(sqlInfo.getQuery());
		else
			csvFormat.add("");

		return csvFormat;
	}

	/**
	 * SQL監視固有のメッセージ情報をExportする。<br>
	 * 
	 * @param monitorInfo 監視情報
	 * @return CSVフォーマット文字列
	 */
	protected ArrayList<String> createMonitorMessage(MonitorInfo monitorInfo) {
		ArrayList<String> csvFormat = new ArrayList<String>();

		ArrayList<String> info = new ArrayList<String>();
		ArrayList<String> warning = new ArrayList<String>();
		ArrayList<String> critical = new ArrayList<String>();

		for(int i=0; i < 2; i++){
			info.add("");
			warning.add("");
			critical.add("");
		}

		ArrayList list = monitorInfo.getNumericValueInfo();
		if(list != null){
			for(int i=0; i < list.size(); i++){
				MonitorNumericValueInfo numericValueInfo = (MonitorNumericValueInfo)list.get(i);
				if(numericValueInfo != null){
					ArrayList<String> priority = null;
					if(PriorityConstant.TYPE_INFO ==  numericValueInfo.getPriority()){
						priority = info;
					}
					else if(PriorityConstant.TYPE_WARNING ==  numericValueInfo.getPriority()){
						priority = warning;
					}
					else if(PriorityConstant.TYPE_CRITICAL ==  numericValueInfo.getPriority()){
						priority = critical;
					}
					else{
						continue;
					}

					//メッセージID
					if (numericValueInfo.getMessageId() != null)
						priority.set(0, numericValueInfo.getMessageId());

					//メッセージ
					if (numericValueInfo.getMessage() != null)
						priority.set(1, numericValueInfo.getMessage());
				}
			}
		}

		csvFormat.addAll(info);
		csvFormat.addAll(warning);
		csvFormat.addAll(critical);

		return csvFormat;
	}

	/**
	 * 監視項目リストを取得する。<br>
	 * 
	 * @return 監視項目一覧
	 */
	protected ArrayList getSnmpList() {

		MonitorSqlController sql = EjbConnectionManager.getConnectionManager().getMonitorSqlController();

		ArrayList records = null;
		try {
			records = sql.getSqlList();
		} catch (Exception e) {
			log.error(Messages.getMsg("ConnectManagerFailed"), e);
			System.exit(14);
		}
		return records;
	}
}