/*
 * Copyright (C) 2005 NTT DATA Corporation
 * 
 */
package org.postgresforest.tool.view.action;

import java.util.ArrayList;
import java.util.Iterator;

import org.eclipse.jface.action.IAction;
import org.postgresforest.tool.action.DbAction;
import org.postgresforest.tool.action.DbInstanceAction;
import org.postgresforest.tool.bean.DbLinkInfo;
import org.postgresforest.tool.bean.ServerInfo;
import org.postgresforest.tool.db.GSCdata;
import org.postgresforest.tool.util.ErrorLog;
import org.postgresforest.tool.util.SessionProperty;
import org.postgresforest.tool.view.ViewUtil;
import org.postgresforest.tool.view.dbinstance.DbInstanceView;
import org.postgresforest.tool.view.menu.AdminMenuView;

/**
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class DelDbInstanceAction extends ActionBase {
    public static final String ID = "org.postgresforest.tool.view.action.DelDbInstanceAction";
    									
	/* (non-Javadoc)
	 * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
	 */
	public void run(IAction action) {
		DbInstanceView view = (DbInstanceView)m_view;
		String dbName = view.getSelectDb();
		int selectId = view.getSelectInstanceId();
		//データベース削除
		if(dbName != "" && selectId >= 0){
			//セッション･プロパティからグローバルシステムカタログを取得
			GSCdata gsc = (GSCdata)SessionProperty.get("gsc");

			//セッション･プロパティからデータベースリンク情報を取得
			ArrayList dbLinkList = getDbLinkList(gsc);
			
			//選択されているデータベースのサーバ情報を取得
			ArrayList dbServer = null;
			for (Iterator iter = dbLinkList.iterator(); iter.hasNext();) {
				DbLinkInfo dbInfo = (DbLinkInfo) iter.next();
				if (dbName.compareTo(dbInfo.getName()) == 0) {
					dbServer = dbInfo.getServer();
					break;
				}
			}

			//
			for (Iterator iter= dbServer.iterator(); iter.hasNext();) {
				ServerInfo serverInfo = (ServerInfo) iter.next();
				if (serverInfo.getId() == selectId) {
					serverInfo.setChkFlag(true);
					break;
				}
			}

			//データベース削除
			DbAction dbAction = new DbAction(gsc);
			try {
				dbAction.del(dbLinkList);
			} catch (Exception e1) {
				e1.printStackTrace();
				ErrorLog.log("", e1);
			}
		}
		
		view.update();
		
		//管理者メニューを更新
		ViewUtil.updateView(AdminMenuView.ID);
	}
	
	/**
	 * データベース一覧の取得
	 *
	 */
	private ArrayList getDbLinkList(GSCdata gsc) {
		ArrayList dbList = null;
		DbInstanceAction dbInstance = new DbInstanceAction(gsc);
		try {
			dbList = dbInstance.getDbLinkList();
		} catch (Exception e) {
			e.printStackTrace();
			ErrorLog.log("", e);
		}
		
		return dbList;
	}
	

}
