/*
 * 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.eclipse.jface.window.Window;
import org.eclipse.ui.IViewPart;
import org.postgresforest.tool.action.DbAction;
import org.postgresforest.tool.action.DbInstanceAction;
import org.postgresforest.tool.bean.AddDbInfo;
import org.postgresforest.tool.bean.ServerInfo;
import org.postgresforest.tool.db.GSCdata;
import org.postgresforest.tool.dialog.adddb.AddDbDialog;
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 AddDbInstanceAction extends ActionBase {
    public static final String ID = "org.postgresforest.tool.view.action.AddDbInstanceAction";
	private AddDbDialog m_dialog;
	
	public void init(IViewPart view) {
		super.init(view);
		m_dialog = new AddDbDialog();

	}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
	 */
	public void run(IAction action) {
		GSCdata gsc = (GSCdata)SessionProperty.get("gsc");
		DbInstanceView dbInstanceView = (DbInstanceView)m_view;
		String dbName = dbInstanceView.getSelectDb(); 
		ArrayList existServerList = dbInstanceView.getSerrerList();
		
		DbInstanceAction dbInstance = new DbInstanceAction(gsc);
		AddDbInfo addDbInfo;
		try {
			addDbInfo = dbInstance.getAddDbInfo();
		} catch (Exception e) {
			ErrorLog.log("", e);
			return;
		}
		 
		// 指定されたDB名の登録されていないインスタンスのリストを作成する
		ArrayList serverList = addDbInfo.getServer();

		for (Iterator iter2 = existServerList.iterator(); iter2.hasNext();) {
			ServerInfo existServerInfo = (ServerInfo) iter2.next();

			for (Iterator iter = serverList.iterator(); iter.hasNext();) {
				ServerInfo severInfo = (ServerInfo) iter.next();
				if( severInfo.getId() == existServerInfo.getId() ){
					serverList.remove(severInfo);
					break;
				}
				
			}
			
		}
		
		//データベース作成ダイアログを表示する
		addDbInfo.setDb(dbName);
		m_dialog.setAddDb(addDbInfo);
		if (m_dialog.open() == Window.OK) {
			addDbInfo = m_dialog.getAddDb();
			//DB作成
			DbAction addDb = new DbAction(gsc);
			if( !addDb.add(addDbInfo) ){
				return;
			}
			
			//データベースビューを更新
			m_view.update();
			
			//管理者メニューを更新
			ViewUtil.updateView(AdminMenuView.ID);

		}		
	}


}
