/*

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

import jp.co.intellilink.hinemos.util.EjbConnectionManager;
import jp.co.intellilink.hinemos.util.Messages;

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

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

/**
 * ノード情報を削除するクラス<br>
 * 
 * @version 1.0.0
 * @since 1.0.0
 */
public class DeleteNode {

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

	/**
	 * ノード情報を削除する。<br>
	 */
	@SuppressWarnings("unchecked")
	public void delete() {
		log.info(Messages.getMsg("Node.Start", new String[]{Messages.getMsg("ImportTool.Delete")}));

		//ノードリスト取得
		ArrayList<Property> idList = getNodeList();

		for(Property property : idList){
			//管理対象
			ArrayList propertyList = PropertyUtil.getProperty(property, NodeProperty.FACILITY_ID);
			String id = (String)((Property)propertyList.get(0)).getValue();

			deleteNodeInfo(id);
		}

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

	/**
	 * ノード情報を削除する。<br>
	 * 
	 * @param facilityId ファシリティID
	 */
	protected void deleteNodeInfo(String facilityId) {
		RepositoryController repository = EjbConnectionManager.getConnectionManager().getRepositoryController();

		try {
			Object[] args = {facilityId};
			log.info(Messages.getMsg("FacilityID", args) + 
					" (" + Messages.getMsg("delete") + ")");

			repository.deleteNode(facilityId);
		} catch (Exception e) {
			log.error(Messages.getMsg("ConnectManagerFailed"), e);
			System.exit(14);
		}
	}

	/**
	 * ファシリティリストを取得する。<br>
	 * 
	 * @return ファシリティ一覧
	 */
	@SuppressWarnings("unchecked")
	protected ArrayList<Property> getNodeList() {

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

		ArrayList<Property> nodeList = new ArrayList<Property>();
		try {
			ArrayList<String> records = repository.getNodeFacilityIdList();
			for(String facilityId : records){
				Property node = repository.getNodeProperty(facilityId, PropertyConstant.MODE_SHOW, Locale.getDefault());
				nodeList.add(node);
			}
		} catch (Exception e) {
			log.error(Messages.getMsg("ConnectManagerFailed"), e);
			System.exit(14);
		}
		return nodeList;
	}
}