/*

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

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.ejb.DuplicateKeyException;

import jp.co.intellilink.hinemos.importtool.util.CheckString;
import jp.co.intellilink.hinemos.importtool.util.Config;
import jp.co.intellilink.hinemos.importtool.util.EjbConnectionManager;
import jp.co.intellilink.hinemos.importtool.util.Messages;
import jp.co.intellilink.hinemos.importtool.util.ReadCsvFile;

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

import com.clustercontrol.bean.DataRangeConstant;
import com.clustercontrol.bean.PriorityConstant;
import com.clustercontrol.monitor.run.bean.MonitorInfo;
import com.clustercontrol.monitor.run.bean.MonitorNumericValueInfo;
import com.clustercontrol.monitor.run.bean.MonitorTabelDefine;
import com.clustercontrol.monitor.run.bean.MonitorTypeConstant;
import com.clustercontrol.sql.bean.MonitorSqlInfo;
import com.clustercontrol.sql.ejb.session.MonitorSqlController;

/**
 * SQL監視情報をインポートするクラス<br>
 * 
 * @version 1.1.0
 * @since 1.1.0
 */
public class ImportMonitorSqlString extends ImportMonitorNumeric {

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

	@SuppressWarnings("unchecked")
	private ArrayList monitorList = null;

	private ArrayList<ArrayList<String>> monitorInfo = null;

	/**
	 * SQL監視情報をインポートする。<br>
	 */
	public void importSql() {
		log.info(Messages.getMsg("ImportTool.Sql.Start", new String[]{Messages.getMsg("ImportTool.Import")}));

		//SQL監視情報のCSVファイルを読み込む
		monitorInfo = ReadCsvFile.readCsvFile(Config.getConfig("Input.Dir.Conf") + "/SQL.csv");

		//監視項目リスト取得
		monitorList = getMonitorList();

		for(ArrayList<String> info : monitorInfo){
			MonitorInfo monitorInfo = createMonitorInfo(info);
			registerMonitorInfo(monitorInfo);
		}

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

	/**
	 * 監視情報オブジェクトを作成する。<br>
	 * 
	 * @see jp.co.intellilink.hinemos.importtool.conf.monitor.ImportMonitor#createMonitorInfo(java.util.ArrayList)
	 */
	@Override
	protected MonitorInfo createMonitorInfo(ArrayList<String> info){
		MonitorInfo monitorInfo = new MonitorInfo();

		//監視基本情報
		createMonitorBase(info, monitorInfo);

		//監視条件情報
		createMonitorRule(info.subList(3, 5), monitorInfo);

		//監視情報
		createMonitorCheck(info.subList(5, 10), monitorInfo);

		//監視判定情報
		createMonitorJudgement(info.subList(10, 15), monitorInfo);

		//監視通知情報
		createMonitorNotify(info.subList(15, 20), monitorInfo);

		//アプリケーション
		createMonitorApplication(info.subList(20, 21), monitorInfo);

		//メッセージ
		createMonitorMessages(info.subList(21, 27), monitorInfo);

		//有効/無効
		createMonitorVaild(info.subList(27, 28), monitorInfo);

		return monitorInfo;
	}

	/**
	 * SQL監視情報を設定する。<br>
	 * 
	 * @param info 監視情報配列
	 * @param monitorInfo 監視情報オブジェクト
	 * 
	 * @see jp.co.intellilink.hinemos.importtool.conf.monitor.ImportMonitor#createMonitorCheck(java.util.List, com.clustercontrol.monitor.run.bean.MonitorInfo)
	 */
	@Override
	protected void createMonitorCheck(List<String> info, MonitorInfo monitorInfo) {
		MonitorSqlInfo sqlInfo = new MonitorSqlInfo();

		//接続先URL
		String url = CheckString.checkLength(info.get(0), DataRangeConstant.VARCHAR_256);
		if(!url.equals(info.get(0))){
			String[] args = { com.clustercontrol.util.Messages.getString("connection.url"), "256" };
			log.warn(Messages.getMsg("ImportTool.Common.2", args));
		}
		sqlInfo.setConnectionUrl(url);
		//接続先DB
		List<List<String>> list = JdbcDriverUtil.getJdbcDriver();
		for(List<String> driver : list){
			String name = driver.get(0);
			if(name.equals(info.get(1))){
				sqlInfo.setJdbcDriver(driver.get(1));
				break;
			}
		}
		//ユーザID
		String user = CheckString.checkLength(info.get(2), DataRangeConstant.VARCHAR_64);
		if(!url.equals(info.get(2))){
			String[] args = { com.clustercontrol.util.Messages.getString("user.id"), "64" };
			log.warn(Messages.getMsg("ImportTool.Common.2", args));
		}
		sqlInfo.setUser(user);
		//パスワード
		String password = CheckString.checkLength(info.get(3), DataRangeConstant.VARCHAR_64);
		if(!password.equals(info.get(3))){
			String[] args = { com.clustercontrol.util.Messages.getString("password"), "64" };
			log.warn(Messages.getMsg("ImportTool.Common.2", args));
		}
		sqlInfo.setPassword(password);
		//SQL
		String sql = CheckString.checkLength(info.get(4), DataRangeConstant.VARCHAR_1024);
		if(!sql.equals(info.get(4))){
			String[] args = { com.clustercontrol.util.Messages.getString("sql.string"), "1024" };
			log.warn(Messages.getMsg("ImportTool.Common.2", args));
		}
		sqlInfo.setQuery(sql);

		monitorInfo.setCheckInfo(sqlInfo);

		monitorInfo.setMonitorType(MonitorTypeConstant.TYPE_NUMERIC);

		super.createMonitorCheck(info, monitorInfo);
	}

	/**
	 * SQL監視固有のメッセージ情報を設定する。<br>
	 * 
	 * @param info 監視情報配列
	 * @param monitorInfo 監視情報オブジェクト
	 */
	@SuppressWarnings("unchecked")
	protected void createMonitorMessages(List<String> info, MonitorInfo monitorInfo) {
		ArrayList<MonitorNumericValueInfo> list = monitorInfo.getJudgementInfo();
		for(MonitorNumericValueInfo numericValueInfo : list){
			if(numericValueInfo.getPriority() == PriorityConstant.TYPE_INFO){
				numericValueInfo.setMessageId(info.get(0));
				numericValueInfo.setMessage(info.get(1));
			}
			else if(numericValueInfo.getPriority() == PriorityConstant.TYPE_WARNING){
				numericValueInfo.setMessageId(info.get(2));
				numericValueInfo.setMessage(info.get(3));
			}
			else if(numericValueInfo.getPriority() == PriorityConstant.TYPE_CRITICAL){
				numericValueInfo.setMessageId(info.get(4));
				numericValueInfo.setMessage(info.get(5));
			}
			
			String id = CheckString.checkLength(numericValueInfo.getMessageId(), DataRangeConstant.VARCHAR_64);
			if(!id.equals(numericValueInfo.getMessageId())){
				String[] args = { com.clustercontrol.util.Messages.getString("message.id"), "64" };
				log.warn(Messages.getMsg("ImportTool.Common.2", args));
			}
			numericValueInfo.setMessageId(id);
			
			String message = CheckString.checkLength(numericValueInfo.getMessage(), DataRangeConstant.VARCHAR_256);
			if(!message.equals(numericValueInfo.getMessage())){
				String[] args = { com.clustercontrol.util.Messages.getString("message"), "256" };
				log.warn(Messages.getMsg("ImportTool.Common.2", args));
			}
			numericValueInfo.setMessage(message);
		}
	}

	/**
	 * 監視情報を登録する。<br>
	 * 
	 * @param info 監視情報オブジェクト
	 */
	protected void registerMonitorInfo(MonitorInfo info) {
		MonitorSqlController sql = EjbConnectionManager.getConnectionManager().getMonitorSqlController();

		try {
			@SuppressWarnings("unchecked")
			ArrayList list = checkMonitorList(info.getMonitorId(), monitorList);
			if(list instanceof ArrayList){
				Date createTime = (Date)list.get(MonitorTabelDefine.CREATE_TIME);
				String createUser = (String)list.get(MonitorTabelDefine.CREATE_USER);
				info.setRegDate(new Timestamp(createTime.getTime()));
				info.setRegUser(createUser);

				Object[] args = {info.getMonitorId()};
				log.info(Messages.getMsg("ImportTool.MonitorID", args) + 
						" (" + Messages.getMsg("modify") + ")");

				sql.modifySql(info);
			}
			else{
				Object[] args = {info.getMonitorId()};
				log.info(Messages.getMsg("ImportTool.MonitorID", args) + 
						" (" + Messages.getMsg("add") + ")");

				sql.addSql(info);
			}
		} catch (DuplicateKeyException e) {
			String args[] = {info.getMonitorId()};
			log.error(Messages.getMsg("ImportTool.Common.1", args));
			System.exit(20);
		} catch (Exception e) {
			log.error(Messages.getMsg("ImportTool.ConnectManagerFailed"), e);
			System.exit(14);
		}
	}

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

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

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