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

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Locale;

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.FacilityConstant;
import com.clustercontrol.bean.FacilityTreeItem;
import com.clustercontrol.repository.bean.FacilityInfo;
import com.clustercontrol.repository.bean.ScopeInfo;
import com.clustercontrol.repository.ejb.session.RepositoryController;

/**
 * スコープ情報を取得するクラス<br>
 * 
 * @version 1.0.0
 * @since 1.0.0
 */
public class ExportScope {
	
	// ログ出力
	private static Log log = LogFactory.getLog(ExportScope.class);

    /**
     * スコープ情報をExportする。<br>
     */
    public void exportScope() {
    	log.info(Messages.getMsg("Scope.Start", new String[]{Messages.getMsg("ExportTool.Export")}));
    	
    	//CSV出力配列を用意
    	ArrayList<ArrayList<String>> csvOutput = new ArrayList<ArrayList<String>>();
    	
    	//ファシリティツリー取得
    	FacilityTreeItem facilityTree = getFacilityTree();
    	getFacilityTreeItem(facilityTree, csvOutput);
		
		//ファシリティ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") + "/SCOPE" + timestamp + ".csv", 
				csvOutput);
		
		log.info(Messages.getMsg("Scope.End", new String[]{Messages.getMsg("ExportTool.Export")}));
    }
    
    /**
     * スコープ情報取得（再帰呼び出し）
     * 
     * @param treeItem
     * @param csvOutput CSV出力文字列配列
     */
    public void getFacilityTreeItem(FacilityTreeItem treeItem, ArrayList<ArrayList<String>> csvOutput) {

        //子ツリーを取得する
        if (treeItem.getData() instanceof FacilityInfo){
        	FacilityInfo info = treeItem.getData();
        	if(info.getFacilityId() != null && 
        			info.getFacilityId().compareTo("") != 0 &&
        			info.getFacilityType() == FacilityConstant.TYPE_SCOPE){
    			Object[] args = {info.getFacilityId()};
    			log.info(Messages.getMsg("FacilityID", args));
        		
    			ScopeInfo scope = getScope(info.getFacilityId());
    			ArrayList<String> csvFormat = createCsvFormat(scope);
            	String parentFacilityId = "";
    			 if(treeItem.getParent() != null){
            		if (treeItem.getParent().getData() instanceof FacilityInfo){
            			FacilityInfo parentInfo = treeItem.getParent().getData();
            			if(parentInfo.getFacilityId() != null && parentInfo.getFacilityId().compareTo("") != 0){
            				parentFacilityId = parentInfo.getFacilityId();
            			}
            		}
            	}
    			csvFormat.add(parentFacilityId);
    			csvOutput.add(csvFormat);
        	}
        }
        
    	FacilityTreeItem[] childrenTreeItem = treeItem.getChildren();
        for (FacilityTreeItem childTreeItem : childrenTreeItem) {
        	getFacilityTreeItem(childTreeItem, csvOutput);
        }
    }
    
    /**
	 * スコープ情報をExportする。<br>
	 * 
	 * @param info スコープ情報
	 * @return CSVフォーマット文字列
	 */
	public ArrayList<String> createCsvFormat(ScopeInfo info) {
		ArrayList<String> csvFormat = new ArrayList<String>();
		
		//ファシリティID
		csvFormat.add(getStringValue(info.getFacilityId()));
		//ファシリティ名
		csvFormat.add(getStringValue(info.getFacilityName()));
		//説明
		csvFormat.add(getStringValue(info.getDescription()));
		
		return csvFormat;
	}
	
	/**
	 * 文字列を取得する。<br>
	 * 
	 * @param values 配列
	 * @return 文字列
	 */
	public String getStringValue(String values) {
		return values;
	}
	
    /**
     * スコープ情報を取得する。<br>
     * 
     * @param facilityId 取得対象のファシリティID
     * @return スコープ情報
     */
    protected ScopeInfo getScope(String facilityId) {

    	RepositoryController repository = EjbConnectionManager.getConnectionManager().getRepositoryController();

    	ScopeInfo info = null;
        try {
        	info = repository.getScopeProperty(facilityId);
        } catch (Exception e) {
			log.error(Messages.getMsg("ConnectManagerFailed"), e);
			System.exit(14);
        }
        return info;
    }
    
    /**
     * ファシリティツリーを取得する。<br>
     * 
     * @return ファシリティツリー
     */
    protected FacilityTreeItem getFacilityTree() {

    	RepositoryController repository = EjbConnectionManager.getConnectionManager().getRepositoryController();

    	FacilityTreeItem facilityTree = null;
        try {
        	facilityTree = repository.getFacilityTree(Locale.getDefault());
        } catch (Exception e) {
			log.error(Messages.getMsg("ConnectManagerFailed"), e);
			System.exit(14);
		}
        return facilityTree;
    }
}