/*
 
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.performance;

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.RunIntervalConstant;
import com.clustercontrol.performance.bean.CollectorItemInfo;
import com.clustercontrol.performance.bean.CollectorProperty;
import com.clustercontrol.performance.ejb.bmp.RecordCollectorData;
import com.clustercontrol.performance.ejb.session.CollectorController;

/**
 * 性能管理機能の実績収集情報を取得するクラス<br>
 * 
 * @version 1.0.0
 * @since 1.0.0
 */
public class ExportPerformance {
	
	// ログ出力
	private static Log log = LogFactory.getLog(ExportPerformance.class);

	/**
     * 性能管理機能の実績収集情報をExportする。<br>
     */
    public void exportPerformance() {
    	log.info(Messages.getMsg("Performance.Start", new String[]{Messages.getMsg("ExportTool.Export")}));
    	
    	//CSV出力配列を用意
    	ArrayList<ArrayList<String>> csvOutput = new ArrayList<ArrayList<String>>();
    	
    	//収集項目リスト取得
    	ArrayList idList = getPerformanceList();
    	
    	if(idList instanceof ArrayList){
			Iterator itr = idList.iterator();
			while(itr.hasNext()){
				ArrayList line = (ArrayList)itr.next();
				
				Object[] args = {(String)line.get(2)};
				log.info(Messages.getMsg("CollectorID", args));
				
				CollectorProperty property = getPerformance((String)line.get(2));
				csvOutput.add(createCsvFormat(property));
			}
			
			//収集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") + "/PERFORMANCE" + timestamp + ".csv", 
				csvOutput);
		
		log.info(Messages.getMsg("Performance.End", new String[]{Messages.getMsg("ExportTool.Export")}));
    }
    
    /**
	 * 性能管理機能の実績収集情報をExportする。<br>
	 * 
	 * @param property 性能管理機能の実績収集情報
	 * @return CSVフォーマット文字列
	 */
	public ArrayList<String> createCsvFormat(CollectorProperty property) {
		ArrayList<String> csvFormat = new ArrayList<String>();
		
		RecordCollectorData record = property.getCollectorData();
		
		//収集ID
		csvFormat.add(record.getCollectorID());
		//説明
		if (record.getLabel() != null)
			csvFormat.add(record.getLabel());
		else
			csvFormat.add("");
		//ファシリティID
		csvFormat.add(record.getFacilityID());
		//収集間隔
		csvFormat.add(RunIntervalConstant.typeToString(record.getIntervalSec()));
		//収集期間
		int period = record.getPeriodMin();
		if(period != -1)
			csvFormat.add(Messages.getMsg("PERIOD_SETTING"));
		else
			csvFormat.add(Messages.getMsg("UNLIMIT_COLLECT"));
		if(period != -1){
			csvFormat.add(Integer.toString(period / 60 / 24));
			csvFormat.add(Integer.toString(period / 60 % 24));
			csvFormat.add(Integer.toString(period % 60));
			csvFormat.add("");
		}else{
			csvFormat.add("");
			csvFormat.add("");
			csvFormat.add("");
			csvFormat.add(Integer.toString(record.getPresavePeriod()));
		}
		//収集項目
		List<CollectorItemInfo> itemList = property.getItemList();
		for(CollectorItemInfo itemInfo : itemList){
			String itemName = CollectorItemCodeFactory.getFullItemName(itemInfo);
			csvFormat.add(itemName);
		}
		
		return csvFormat;
	}

    /**
     * 性能管理機能の実績収集情報を取得する。<br>
     * 
     * @param collectorId 取得対象の収集ID
     * @return 性能管理機能の実績収集情報
     */
    protected CollectorProperty getPerformance(String collectorId) {

    	CollectorController perf = EjbConnectionManager.getConnectionManager().getCollectorController();

    	CollectorProperty property = null;
        try {
        	property = perf.getCollectorProperty(collectorId);
        } catch (Exception e) {
			log.error(Messages.getMsg("ConnectManagerFailed"), e);
			System.exit(14);
        }
        return property;
    }
    
    /**
     * 収集項目リストを取得する。<br>
     * 
     * @return 収集項目一覧
     */
    protected ArrayList getPerformanceList() {

    	CollectorController perf = EjbConnectionManager.getConnectionManager().getCollectorController();

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