/*

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.logtransfer;

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

import javax.ejb.DuplicateKeyException;

import jp.co.intellilink.hinemos.util.CheckString;
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.ReadCsvFile;
import jp.co.intellilink.hinemos.util.RepositoryUtil;

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

import com.clustercontrol.bean.DataRangeConstant;
import com.clustercontrol.bean.ValidConstant;
import com.clustercontrol.bean.YesNoConstant;
import com.clustercontrol.logtransfer.bean.LogTransferFileInfo;
import com.clustercontrol.logtransfer.bean.LogTransferInfo;
import com.clustercontrol.logtransfer.bean.LogTransferTabelDefine;
import com.clustercontrol.logtransfer.ejb.session.LogTransferController;

/**
 * ログ転送情報をインポートするクラス<br>
 * 
 * @version 1.0.0
 * @since 1.0.0
 */
public class ImportLogTransfer {

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

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

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

	/**
	 * ログ転送情報をインポートする。<br>
	 */
	public void importLogTransfer() {
		log.info(Messages.getMsg("LogTransfer.Start", new String[]{Messages.getMsg("ImportTool.Import")}));

		//ログ転送情報のCSVファイルを読み込む
		logTransferInfos = ReadCsvFile.readCsvFile(Config.getConfig("Import.Dir") + "/LOGTRANSFER.csv");

		//転送項目リスト取得
		logTransferList = getLogTransferList();

		for(ArrayList<String> info : logTransferInfos){
			LogTransferInfo ｔransferInfo = createMaintenanceInfo(info);
			registerLogTransferInfo(ｔransferInfo);
		}

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

	/**
	 * ログ転送情報を作成する。<br>
	 * 
	 * @param info ログ転送情報
	 * @return ログ転送情報オブジェクト
	 */
	public LogTransferInfo createMaintenanceInfo(ArrayList<String> info) {
		LogTransferInfo transferInfo = new LogTransferInfo();

		//転送ID
		String id = CheckString.checkLength(info.get(0), DataRangeConstant.VARCHAR_64);
		if(!id.equals(info.get(0))){
			String[] args = { com.clustercontrol.util.Messages.getString("logtransfer.id"), "64" };
			log.error(Messages.getMsg("ImportTool.Common.2", args));
			System.exit(20);
		}
		transferInfo.setTransferId(id);
		//説明
		String description = CheckString.checkLength(info.get(1), DataRangeConstant.VARCHAR_256);
		if(!description.equals(info.get(1))){
			String[] args = { com.clustercontrol.util.Messages.getString("description"), "256" };
			log.warn(Messages.getMsg("ImportTool.Common.2", args));
		}
		transferInfo.setDescription(info.get(1));
		//ファシリティID
		transferInfo.setFacilityId(info.get(2));
		if(!RepositoryUtil.findFacilityId(info.get(2))){
			String args[] = {transferInfo.getTransferId(), info.get(2)};
			log.error(Messages.getMsg("ImportTool.Repository.1", args));
			System.exit(20);
		}

		ArrayList<LogTransferFileInfo> fileInfos = new ArrayList<LogTransferFileInfo>();
		LogTransferFileInfo fileInfo = new LogTransferFileInfo();
		//ファイルパス
		String filePath = CheckString.checkLength(info.get(3), DataRangeConstant.VARCHAR_4096);
		if(!filePath.equals(info.get(3))){
			String[] args = { com.clustercontrol.util.Messages.getString("description"), "4096" };
			log.warn(Messages.getMsg("ImportTool.Common.2", args));
		}
		fileInfo.setFilePath(filePath);
		//動作間隔
		fileInfo.setRunInterval(Integer.parseInt(info.get(4)));
		//最初にファイルをチェック
		fileInfo.setExistenceFlg(YesNoConstant.stringToType(info.get(5)));
		//有効・無効
		fileInfo.setValid(ValidConstant.stringToType(info.get(6)));
		fileInfos.add(fileInfo);
		transferInfo.setFileInfo(fileInfos);

		//有効/無効
		transferInfo.setValid(ValidConstant.stringToType(info.get(7)));

		return transferInfo;
	}

	/**
	 * 転送項目一覧に指定した転送IDが存在するかチェックする。<br>
	 * 
	 * @param transferId 転送ID
	 * @return チェック結果
	 */
	@SuppressWarnings("unchecked")
	protected ArrayList checkLogTransferList(String transferId) {

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

				String id = (String)line.get(0);
				if(id.compareTo(transferId) == 0)
					return line;
			}
		}

		return null;
	}

	/**
	 * ログ転送情報を登録する。<br>
	 * 
	 * @param transferInfo ログ転送情報
	 */
	protected void registerLogTransferInfo(LogTransferInfo transferInfo) {

		LogTransferController transfer = EjbConnectionManager.getConnectionManager().getLogTransferController();

		try {
			@SuppressWarnings("unchecked")
			ArrayList line = checkLogTransferList(transferInfo.getTransferId());
			if(line instanceof ArrayList){
				Date createTime = (Date)line.get(LogTransferTabelDefine.CREATE_TIME);
				String createUser = (String)line.get(LogTransferTabelDefine.CREATE_USER);
				transferInfo.setRegDate(new Timestamp(createTime.getTime()));
				transferInfo.setRegUser(createUser);

				Object[] args = {transferInfo.getTransferId()};
				log.info(Messages.getMsg("TransferID", args) + 
						" (" + Messages.getMsg("modify") + ")");

				transfer.modifyLogTransfer(transferInfo);
			}
			else{
				Object[] args = {transferInfo.getTransferId()};
				log.info(Messages.getMsg("TransferID", args) + 
						" (" + Messages.getMsg("add") + ")");

				transfer.addLogTransfer(transferInfo);
			}
		} catch (DuplicateKeyException e) {
			String args[] = {transferInfo.getTransferId()};
			log.error(Messages.getMsg("ImportTool.Common.1", args));
			System.exit(20);
		} catch (Exception e) {
			log.error(Messages.getMsg("ConnectManagerFailed"), e);
			System.exit(14);
		}
	}

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

		LogTransferController transfer = EjbConnectionManager.getConnectionManager().getLogTransferController();

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