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

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.custom.TableTree;
import org.eclipse.swt.custom.TableTreeItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.postgresforest.tool.action.GscAction;
import org.postgresforest.tool.bean.InstanceNode;
import org.postgresforest.tool.bean.ServerInfo;
import org.postgresforest.tool.bean.TreeNode;
import org.postgresforest.tool.db.GSCdata;
import org.postgresforest.tool.util.ErrorLog;
import org.postgresforest.tool.util.Messages;
import org.postgresforest.tool.util.SessionProperty;
import org.postgresforest.tool.view.serverstatus.ServerStatusView;

/**
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class DelGscAction extends ActionBase {
    public static final String ID = "org.postgresforest.tool.view.action.DelGscAction";
	/* (non-Javadoc)
	 * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
	 */
	public void run(IAction action) {
		//セッション･プロパティからグローバルシステムカタログを取得
		GSCdata gsc = (GSCdata)SessionProperty.get("gsc");
		
		//GscView view = (GscView)m_view;
		ServerStatusView view = (ServerStatusView)m_view;
		boolean objectCheck = false;
		
		//最後のGSCの削除の場合、確認メッセージを表示する
		if(view.isLastGsc()){
			Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
			if(!MessageDialog.openQuestion(shell, 
					Messages.getString("button.delete"), 
					Messages.getString("message.delgsc.confirm"))){
				return ;
			}
		}
		
		//String dbName = view.getDbName();
		String id = view.getSelectId();
		TableTree tblTree = view.getTableTree();
		TableTreeItem[] arrItem = tblTree.getSelection();
		ServerInfo serverInfo = null;
		String dbName = "";
		if(arrItem.length == 1){
			TableTreeItem dbNameItem = arrItem[0];
			if(dbNameItem.getData() instanceof TreeNode){
				TreeNode dbNameNode = (TreeNode)dbNameItem.getData();
				dbName = dbNameNode.getContent();
				TableTreeItem instanceItem = dbNameItem.getParentItem();
				if(instanceItem.getData() instanceof InstanceNode){
					InstanceNode instanceNode = (InstanceNode)instanceItem.getData();
					serverInfo = instanceNode.getServerInfo();
					objectCheck = true;
					
				}
			}
		}
		if(objectCheck){
			id = Integer.toString(serverInfo.getId());
			//グローバルシステムカタログ削除
			if(id != ""){
				GscAction delGsc = new GscAction(gsc);
				try {
					delGsc.delGsc(dbName, id );
					
				} catch (Exception e1) {
					e1.printStackTrace();
					ErrorLog.log("", e1);
				}
			}
		}
		
		view.update();
	}


}
