/*

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

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.Locale;

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 jp.co.intellilink.hinemos.importtool.util.StringListComparator;

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

import com.clustercontrol.bean.DataRangeConstant;
import com.clustercontrol.bean.Property;
import com.clustercontrol.bean.PropertyConstant;
import com.clustercontrol.repository.ejb.session.RepositoryController;
import com.clustercontrol.repository.factory.ScopeProperty;
import com.clustercontrol.util.PropertyUtil;

/**
 * スコープ情報をインポートするクラス<br>
 * 
 * @version 1.1.0
 * @since 1.1.0
 */
public class ImportScope {

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

	@SuppressWarnings("unchecked")
	private ArrayList<Property> scopeList = null;

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

	/**
	 * スコープ情報をインポートする。<br>
	 */
	@SuppressWarnings("unchecked")
	public void importScope() {
		log.info(Messages.getMsg("ImportTool.Scope.Start", new String[]{Messages.getMsg("ImportTool.Import")}));

		//スコープ情報のCSVファイルを読み込む
		scopeInfos = ReadCsvFile.readCsvFile(Config.getConfig("Input.Dir.Conf") + "/SCOPE.csv");

		//スコープリスト取得
		scopeList = getScopeList();

		//ファシリティIDでソート
		Collections.sort(scopeInfos, new StringListComparator(0));
		//親ファシリティIDでソート
		Collections.sort(scopeInfos, new StringListComparator(3));

		for(ArrayList<String> info : scopeInfos){
			String facilityId = info.get(0);
			if(!facilityId.matches("(INTERNAL|REGISTERED|UNREGISTERED)")){
				Property property = createScopeInfo(info);

				String parentFacilityId = "";
				if(info.size() >= 4)
					parentFacilityId = info.get(3);

				registerScopeInfo(parentFacilityId, property);
			}
		}
		
		log.info(Messages.getMsg("ImportTool.Scope.End", new String[]{Messages.getMsg("ImportTool.Import")}));

	}

	/**
	 * スコープ情報を作成する。<br>
	 * 
	 * @param info スコープ情報配列
	 * @return スコープ情報オブジェクト
	 */
	public Property createScopeInfo(ArrayList<String> info) {
		Property property = getScopeProperty();

		@SuppressWarnings("unchecked")
		ArrayList propertyList = null;

		//ファシリティID
		String id = CheckString.checkLength(info.get(0), DataRangeConstant.VARCHAR_64);
		if(!id.equals(info.get(0))){
			String[] args = { com.clustercontrol.util.Messages.getString("facility.id"), "64" };
			log.error(Messages.getMsg("ImportTool.Common.2", args));
			System.exit(20);
		}
		propertyList = PropertyUtil.getProperty(property, ScopeProperty.FACILITY_ID);
		((Property)propertyList.get(0)).setValue(id);
		//ファシリティ名
		String name = CheckString.checkLength(info.get(1), DataRangeConstant.VARCHAR_256);
		if(!name.equals(info.get(1))){
			String[] args = { com.clustercontrol.util.Messages.getString("facility.name"), "256" };
			log.warn(Messages.getMsg("ImportTool.Common.2", args));
		}
		propertyList = PropertyUtil.getProperty(property, ScopeProperty.FACILITY_NAME);
		((Property)propertyList.get(0)).setValue(name);
		//説明
		String description = CheckString.checkLength(info.get(2), DataRangeConstant.VARCHAR_1024);
		if(!description.equals(info.get(2))){
			String[] args = { com.clustercontrol.util.Messages.getString("description"), "1024" };
			log.warn(Messages.getMsg("ImportTool.Common.2", args));
		}
		propertyList = PropertyUtil.getProperty(property, ScopeProperty.DESCRIPTION);
		((Property)propertyList.get(0)).setValue(description);

		return property;
	}

	/**
	 * スコープ一覧に指定したファシリティIDが存在するかチェックする。<br>
	 * 
	 * @param facilityId ファシリティID
	 * @return チェック結果
	 */
	protected Property checkScopeList(String facilityId) {
		@SuppressWarnings("unchecked")
		ArrayList propertyList = null;

		for(Property property : scopeList){

			propertyList = PropertyUtil.getProperty(property, ScopeProperty.FACILITY_ID);
			String id = (String)((Property)propertyList.get(0)).getValue();

			if(id.compareTo(facilityId) == 0)
				return property;
		}

		return null;
	}

	/**
	 * スコープ情報を登録する。<br>
	 * 
	 * @param property スコープ情報
	 */
	protected void registerScopeInfo(String parentFacilityId, Property property) {

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

		@SuppressWarnings("unchecked")
		ArrayList propertyList = null;

		propertyList = PropertyUtil.getProperty(property, ScopeProperty.FACILITY_ID);
		String facilityId = (String)((Property)propertyList.get(0)).getValue();

		try {
			@SuppressWarnings("unchecked")
			Property line = checkScopeList(facilityId);
			if(line instanceof Property){
				Object[] args = {facilityId};
				log.info(Messages.getMsg("ImportTool.FacilityID", args) + 
						" (" + Messages.getMsg("modify") + ")");

				repository.modifyScope(property);
			}
			else{
				Object[] args = {facilityId};
				log.info(Messages.getMsg("ImportTool.FacilityID", args) + 
						" (" + Messages.getMsg("add") + ")");

				repository.addScope(parentFacilityId, property);
			}
		} catch (DuplicateKeyException e) {
			String args[] = {facilityId};
			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 スコーププロパティ
	 */
	protected Property getScopeProperty() {

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

		Property property = null;
		try {
			property = repository.getScopeProperty("", PropertyConstant.MODE_ADD, Locale.getDefault());
		} catch (Exception e) {
			log.error(Messages.getMsg("ImportTool.ConnectManagerFailed"), e);
			System.exit(14);
		}
		return property;
	}

	/**
	 * スコープリストを取得する。<br>
	 * 
	 * @return スコープリスト
	 */
	@SuppressWarnings("unchecked")
	protected ArrayList getScopeList() {

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

		ArrayList<Property> scopeList = new ArrayList<Property>();
		try {
			ArrayList records = repository.getScopeList("");
			if(records instanceof ArrayList){
				Iterator itr = records.iterator();
				while(itr.hasNext()){
					ArrayList line = (ArrayList)itr.next();
					String facilityId = (String)line.get(0);
					Property scope = repository.getScopeProperty(facilityId, PropertyConstant.MODE_SHOW, Locale.getDefault());
					scopeList.add(scope);
				}
			}
		} catch (Exception e) {
			log.error(Messages.getMsg("ImportTool.ConnectManagerFailed"), e);
			System.exit(14);
		}
		return scopeList;
	}
}