package hiro.yoshioka.application.chihuahua;

import hiro.yoshioka.ast.sql.util.BindInfo;
import hiro.yoshioka.ast.sql.util.IProposalableParserUtil;
import hiro.yoshioka.ast.sql.util.ProposalParserFactory;
import hiro.yoshioka.ast.sql.util.WolfMongoProposalParserUtil;
import hiro.yoshioka.sdh.CSVRecordDataHolder;
import hiro.yoshioka.sdh.DatabaseType;
import hiro.yoshioka.sdh.RDHTableViewer;
import hiro.yoshioka.sdh.ResultSetDataHolder;
import hiro.yoshioka.sql.ITransactionSQL;
import hiro.yoshioka.sql.engine.GettingResourceRequest;
import hiro.yoshioka.sql.engine.Request;
import hiro.yoshioka.sql.engine.RequestAdaptor;
import hiro.yoshioka.sql.engine.SQLOperationType;
import hiro.yoshioka.sql.engine.SQLServerThread;
import hiro.yoshioka.sql.engine.TransactionRequest;
import hiro.yoshioka.sql.notes.AbsNotesRunner;
import hiro.yoshioka.sql.params.ConnectionProperties;
import hiro.yoshioka.sql.resource.DBRoot;
import hiro.yoshioka.sql.resource.IDBSchema;
import hiro.yoshioka.sql.resource.IDBTable;
import hiro.yoshioka.sql.resource.notes.NotesDBTable;
import hiro.yoshioka.sql.resource.view.DBResourceCompositeMaker;
import hiro.yoshioka.sql.resource.view.DBResourceTreeSelection;
import hiro.yoshioka.sql.resource.view.DBResourceTreeViewer;
import hiro.yoshioka.sql.resource.view.IDBResourceTreeViewerContextMenuListener;
import hiro.yoshioka.sql.resource.view.IDBResourceTreeViewerListener;
import hiro.yoshioka.sql.util.DefaultDatabaseComparingDialog;
import hiro.yoshioka.sql.util.DefaultMirroringDialog;
import hiro.yoshioka.sql.util.SelectTableDialog;
import hiro.yoshioka.util.CSVUtil;
import hiro.yoshioka.util.ColorNameEnum;
import hiro.yoshioka.util.ColorUtil;
import hiro.yoshioka.util.ImageUtil;
import hiro.yoshioka.util.ProgramUtil;
import hiro.yoshioka.util.StringUtil;

import java.io.File;
import java.util.Date;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.StatusLineManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.program.Program;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class ChihuahuaDBClient extends ApplicationWindow implements
		IDBResourceTreeViewerContextMenuListener {
	StatusLineManager slm = new StatusLineManager();
	Display display;
	static SQLServerThread server;
	public DBResourceTreeViewer treeViewer;
	Text treeSearchText;
	Text sqlText;
	public RDHTableViewer v;
	private IDBTable viewerTable;
	ProgressMonitorDialog progressDialog;
	Button btExecuteQuery;
	private ConnectionProperties rdhViewerConnection;
	static {
		java.util.logging.Logger.getLogger("org.apache.commons.httpclient")
				.setLevel(java.util.logging.Level.FINEST);

		System.setProperty("org.apache.commons.logging.Log",
				"org.apache.commons.logging.impl.SimpleLog");
		System.setProperty("org.apache.commons.logging.simplelog.showdatetime",
				"false");
		System.setProperty(
				"org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient",
				"info");
	}

	public ChihuahuaDBClient(Shell shell) {
		super(shell);
		addStatusLine();
	}

	@Override
	public boolean close() {
		server.dispose();
		return super.close();
	}

	@Override
	protected StatusLineManager createStatusLineManager() {
		return slm;
	}

	public static void main(String[] args) {
		Shell shell = new Shell();
		ChihuahuaDBClient app = new ChihuahuaDBClient(shell);

		app.setBlockOnOpen(true);
		app.open();
		Display.getCurrent().dispose();
	}

	private GridLayout createGridLayout(int num) {
		GridLayout layout = new GridLayout(num, false);
		layout.horizontalSpacing = 1;
		layout.verticalSpacing = 0;
		layout.marginBottom = 0;
		layout.marginHeight = 0;
		layout.marginLeft = 0;
		layout.marginRight = 0;
		layout.marginTop = 0;
		layout.marginWidth = 1;
		return layout;
	}

	private void hookContextMenu() {
		try {
			MenuManager menuMgr = new MenuManager("#PopupMenu");
			menuMgr.setRemoveAllWhenShown(true);
			menuMgr.addMenuListener(new IMenuListener() {
				public void menuAboutToShow(IMenuManager manager) {
					ConnectionProperties prop = treeViewer
							.getLatestSelectedConnectionProperties();
					if (prop == null || !prop.getDatabaseType().isDomino()) {
						return;
					}
					final ResultSetDataHolder rdh = v.getRDH();
					if (rdh.getIndexByName(AbsNotesRunner.HttpURL) >= 0) {
						if (rdh.getRowCount() > 0 && viewerTable != null) {
							NotesDBTable notesTbl = (NotesDBTable) viewerTable;
							manager.add(new Action("browse") {
								public void run() {
									int rowIdx = v.getLastSelectedRow();
									String url = rdh.getStringData(rowIdx,
											AbsNotesRunner.HttpURL);
									System.out.println("url=" + url);
									Program.launch(url);
								};
							});
						}
					}
				}
			});
			Menu menu = menuMgr.createContextMenu(v.getControl());

			v.getControl().setMenu(menu);
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

	@Override
	protected Control createContents(Composite parent) {
		server = SQLServerThread.getSQLServer();
		File configDir = new File("config");
		server.init(configDir);

		display = parent.getDisplay();
		getShell().setText("Chihuahua DB Client");
		final SashForm sashMain = new SashForm(parent, SWT.BORDER
				| SWT.VERTICAL);

		final SashForm sashTop = new SashForm(sashMain, SWT.BORDER
				| SWT.HORIZONTAL);
		Composite treeComposite = new Composite(sashTop, SWT.NONE);
		GridLayout gl = createGridLayout(1);
		treeComposite.setLayout(gl);

		DBResourceCompositeMaker maker = DBResourceCompositeMaker
				.getInstance(false);
		maker.createControl(treeComposite);
		maker.getMainComposite()
				.setLayoutData(new GridData(GridData.FILL_BOTH));
		sqlText = new Text(sashTop, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL
				| SWT.BORDER);

		sqlText.addKeyListener(new KeyAdapter() {
			public void keyPressed(KeyEvent e) {
				if ((e.stateMask == SWT.COMMAND || e.stateMask == SWT.CTRL)
						&& (e.keyCode == 'a' || e.keyCode == 'A')) {
					sqlText.selectAll();
				}
			}
		});
		treeViewer = maker.getTreeViewer();
		treeViewer.setInput(server.getConnectionSet());
		treeSearchText = maker.getSearchText();
		Composite bottomComposite = new Composite(sashMain, SWT.NONE);
		bottomComposite.setLayout(createGridLayout(1));
		v = new RDHTableViewer2(bottomComposite);
		v.getTable().setLayoutData(new GridData(GridData.FILL_BOTH));
		// hookContextMenu();
		treeViewer.setDBResourceTreeViewerContextMenuListener(this);
		treeViewer
				.addDBResourceTreeViewerListener(new IDBResourceTreeViewerListener() {

					@Override
					public void fireSelectionChanged(
							ConnectionProperties connectionProperties,
							Object selection) {
					}

					@Override
					public void fireDoubleClick(ConnectionProperties prop,
							Object selection) {
						try {
							if (selection instanceof ConnectionProperties) {
								if (!prop.isConnected()) {
									connect(prop);
								}
							} else if (selection instanceof IDBSchema) {
								if (prop.isConnected()) {
									IDBSchema schema = (IDBSchema) selection;
									if (schema.childrenNum() == 0) {
										refreshSchemaResources(schema);
									}
								}
							} else if (selection instanceof IDBTable) {
								if (!prop.isConnected()) {
									MessageDialog.openError(getShell(),
											"Connection Error",
											"Now disconnected...");
									return;
								}
								IDBTable tbl = (IDBTable) selection;
								if (tbl.isTable() || tbl.isView()) {
									if (tbl.getColumns().length == 0) {
										tbl = refreshTableColumns(tbl);
										SQLServerThread.getSQLServer()
												.saveConnectionProperties();
									}
								}
								viewerTable = tbl;
								SelectTableDialog dialog = new SelectTableDialog(
										prop, display.getActiveShell(), tbl,
										new RequestAdaptor() {
											@Override
											public void called_done(
													final Request request,
													SQLOperationType operation,
													final ConnectionProperties properteis,
													final Object o) {
												System.out.println("done called !!!!!!!!!!  "
														+ request
																.hasException());

												ResultSetDataHolder rd = (ResultSetDataHolder) o;

												display.asyncExec(new Runnable() {
													@Override
													public void run() {
														System.out
																.println("async done called !!!!!!!!!!");
														if (o == null) {
															System.err
																	.println("o is null");
															System.err.println("o has exception"
																	+ request
																			.hasException());
															request.getException()
																	.printStackTrace();
														} else {
															v.setInputAdjustDatum((CSVRecordDataHolder) o);
														}
														rdhViewerConnection = properteis;
													}
												});
												treeViewer
														.refreshResourceLazy(properteis
																.getDBRootResource()
																.getRecentryUsedResource());
											}
										});
								dialog.setBlockOnOpen(true);
								int dialogResult = dialog.open();
								if (dialogResult == SelectTableDialog.OK) {
									sqlText.setText(dialog
											.getSqlStatementString());
									// TODO:
									// treeViewer.refresh();
								}
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});

		Composite btnPanel = new Composite(bottomComposite, SWT.BOTTOM);
		btnPanel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		btnPanel.setBackground(ColorUtil.getColor(ColorNameEnum.CHANGE));
		btnPanel.setLayout(new FillLayout());

		btExecuteQuery = new Button(btnPanel, SWT.BORDER);
		btExecuteQuery.setText("Execute Query");
		btExecuteQuery.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				ConnectionProperties prop = treeViewer
						.getLatestSelectedConnectionProperties();
				executeQuery(prop);
			}

		});

		Button delSave = new Button(btnPanel, SWT.BORDER);
		delSave.setText("save");
		delSave.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				CSVRecordDataHolder rdh = v.getCDH();
				Date d = new Date();
				rdh.saveCSV(
						new File(String.format("C:/saved_%tm%td%tH%tM.csv", d,
								d, d, d)), "Utf-8",
						CSVUtil.QUOTE_DOUBLE_QUOTE_SEPARATE_TAB, false);
			}
		});
		Button adjustDatum = new Button(btnPanel, SWT.BORDER);
		adjustDatum.setText("adjustDatum");
		adjustDatum.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				CSVRecordDataHolder rdh = v.getCDH();
				v.setInputAdjustDatum(rdh);
			}
		});

		Button adjustArea = new Button(btnPanel, SWT.BORDER);
		adjustArea.setText("adjustArea");
		adjustArea.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				CSVRecordDataHolder rdh = v.getCDH();
				v.setInputAdjustArea(rdh);
			}
		});
		adjustDatum.setImage(ImageUtil.getImage(ImageUtil.ACTION_82_ERROR));
		adjustArea.setImage(ImageUtil.getImage(ImageUtil.ACTION_43_GO));

		Rectangle rect = display.getBounds();
		int width = 800;
		if (rect.width > 1024) {
			width = 1024;
		}
		int height = 480;
		if (rect.height > 800) {
			height = 800;
		} else if (rect.height > 640) {
			height = 640;
		}
		parent.setSize(width, height);

		return parent;

	}

	private IDBSchema refreshSchemaResources(IDBSchema schema) {
		ConnectionProperties prop = treeViewer
				.getLatestSelectedConnectionProperties();
		GettingResourceRequest req = new GettingResourceRequest(prop);
		req.targetType = GettingResourceRequest.GettingTarget.ONLY_SCHEMA;
		req.selectionResource = schema;
		try {
			if (prop != null && prop.isConnected()) {
				SQLServerThread.runNowThisRequest(req);
			}

		} catch (Exception ee) {
			ee.printStackTrace();
		}
		return schema;

	}

	private IDBTable refreshTableColumns(IDBTable tbl) {
		ConnectionProperties prop = treeViewer
				.getLatestSelectedConnectionProperties();
		GettingResourceRequest req = new GettingResourceRequest(prop);
		req.targetType = GettingResourceRequest.GettingTarget.ONLY_TABLE;
		req.selectionResource = tbl;

		try {
			if (prop != null && prop.isConnected()) {
				if (SQLServerThread.runNowThisRequest(req)) {
				} else {
					System.err.println(" refresh failuer");
				}
			}
		} catch (Exception ee) {
			ee.printStackTrace();
		}
		return tbl;

	}

	private IProposalableParserUtil getParserUtil(
			ConnectionProperties connectionProperties, String sql_statement) {
		ProposalParserFactory factory = ProposalParserFactory
				.createFactory(connectionProperties.getDriverName());
		return factory.createParserUtil(sql_statement,
				connectionProperties.getDBRootResource());
	}

	private void executeQuery(ConnectionProperties connectionProperties) {
		IProposalableParserUtil util = getParserUtil(connectionProperties,
				sqlText.getText());
		util.parse();

		if (!util.doQuery()) {
			MessageDialog
					.openWarning(Display.getCurrent().getActiveShell(), null,
							"Chihuahua can't accept Transactional Request..., only DML.");
			return;
		}
		TransactionRequest tran_request = null;
		BindInfo[] binds = util.binds();
		if (binds.length > 0) {

		} else {
			switch (connectionProperties.getDatabaseType()) {
			case MONGO:
				WolfMongoProposalParserUtil mUtil = (WolfMongoProposalParserUtil) util;
				tran_request = mUtil
						.createTransactionRequest(connectionProperties);

				// req.setMaxRownum(fMaxRowsFromDB.getSelection());
				tran_request.setPartName(util.getFirstTable().getName());
				break;
			case DOMINO:
				tran_request = util
						.createTransactionRequest(connectionProperties);

				// req.setMaxRownum(fMaxRowsFromDB.getSelection());
				tran_request.setPartName(util.getFirstTable().getName());
				break;
			default:
				tran_request = new TransactionRequest(
						SQLOperationType.PREPARED_EXECUTE_QUERY,
						connectionProperties, util.getSQLStatement());
				break;
			}
			tran_request.setMaxRownum(Integer.MAX_VALUE);
		}
		tran_request.addListener(new RequestAdaptor() {
			@Override
			public void called_done(final Request request,
					SQLOperationType operation,
					final ConnectionProperties properteis, final Object o) {
				System.out.println("done caleed executeQuery");
				display.asyncExec(new Runnable() {
					@Override
					public void run() {
						ResultSetDataHolder rdh = null;
						if (request.hasException()) {
							rdh = new ResultSetDataHolder(
									new String[] { "exceptins" });
							Throwable ex = request.getException();
							rdh.addRow(new String[] {

							ex.getMessage() });
							for (StackTraceElement line : ex.getStackTrace()) {
								rdh.addRow(new String[] { line.toString() });
							}
							Throwable ex2 = ex.getCause();
							if (ex2 != null) {
								Throwable ex3 = ex2.getCause();
								if (ex3 != null) {
									rdh.addRow(new String[] {
											StringUtil.EMPTY_STRING,
											"    " + ex3.getMessage() });
									for (StackTraceElement line : ex3
											.getStackTrace()) {
										rdh.addRow(new String[] {
												StringUtil.EMPTY_STRING,
												"    " + line.toString() });
									}
								}
							}

						} else {
							rdh = (ResultSetDataHolder) o;
						}
						v.setInputAdjustDatum(rdh);
						rdhViewerConnection = properteis;

						setStatus("done...");
					}
				});
			}
		});
		SQLServerThread.putRequest(tran_request);
	}

	private void connect(ConnectionProperties connectionProperties) {
		final Request request = new Request(SQLOperationType.CONNECT,
				connectionProperties);
		// request.addListener(treeViewer);
		server.putRequest(request);
		request.addListener(new MyConnectionRequestAdaptor());
	}

	private void disConnect(ConnectionProperties connectionProperties) {
		final Request request = new Request(SQLOperationType.CLOSE,
				connectionProperties);
		// request.addListener(treeViewer);
		server.putRequest(request);
		request.addListener(new MyDisconnectRequestAdaptor());
	}

	private void captureResource(ConnectionProperties connectionProperties) {
		GettingResourceRequest request = new GettingResourceRequest(
				connectionProperties);
		setStatus("CaptureResoruce...");

		SQLServerThread.putRequest(request);
		// request.addListener(treeViewer);
		request.addListener(new RequestAdaptor() {
			int total = 0;
			String name;

			private void setMessage(final String s) {
				display.asyncExec(new Runnable() {
					@Override
					public void run() {
						setStatus(s);
					}
				});
			}

			@Override
			public void beginTask(String taskName, int row) {
				total = 0;
				setMessage("begin[" + taskName + "] row=" + row);
				this.name = taskName;
			}

			@Override
			public void worked(int j) {
				total++;
				String s = StringUtil.nvl(name);
				int n = total % 30;
				for (int i = 0; i < n; i++) {
					s += ".";
				}
				// System.out.println("s=" + s);
				setMessage(s);
			}

			@Override
			public void subTask(final String subTaskName) {
				total = 0;
				setMessage("CaptureResoruce... [" + subTaskName + "]");
			}

			@Override
			public void called_done(Request request,
					SQLOperationType operation,
					ConnectionProperties properteis, Object o) {
				ITransactionSQL sql = SQLServerThread
						.getSQLServer()
						.getTransactionSQL(
								treeViewer
										.getLatestSelectedConnectionProperties());
				System.out.println("done sql:" + sql);
				if (sql == null) {
					return;
				}
				DBRoot root = sql.getRoot();
				final ResultSetDataHolder rdh = new ResultSetDataHolder(
						new String[] { "DB", "Collection" });
				for (IDBSchema schema : root.getSchemas()) {
					if (root.hasChildren()) {
						rdh.addRow(new String[] { schema.getName(),
								StringUtil.EMPTY_STRING });
					} else {
						for (IDBTable table : schema.getTableOrViews()) {
							rdh.addRow(new String[] { schema.getName(),
									table.getName() });
						}
					}
				}
				display.asyncExec(new Runnable() {
					@Override
					public void run() {
						setStatus("CaptureResoruce... [DONE]");
						v.setInputAdjustDatum(rdh);
					}
				});
			}
		});
	}

	//
	class RDHTableViewer2 extends RDHTableViewer {

		public RDHTableViewer2(Composite parent) {
			super(parent);
		}

		public void menuAboutToShow(IMenuManager manager) {
			ConnectionProperties prop = rdhViewerConnection;
			if (prop == null) {
				return;
			}
			Action action = null;
			final ResultSetDataHolder rdh = getRDH();
			switch (prop.getDatabaseType()) {
			case ORACLE:
				break;
			case DOMINO:
				if (rdh != null && rdh.getRowCount() > 0) {
					// NotesDBTable notesTbl = (NotesDBTable)
					// viewerTable;
					// if (notesTbl.canMakeHtmlString()) {
					// String html = notesTbl.toHtmlString(rdh,
					// v.getLastSelectedRow());
					// FileUtil.writeFile(new File("C:/h.html"),
					// html, "UTF-8");
					// } else {
					// MessageDialog
					// .openWarning(v.getTable()
					// .getShell(), "Notice",
					// "nothing DDL. check your configuration. ");
					// }
					Program notesClient = ProgramUtil.getNotesProgram();
					if (notesClient != null
							&& rdh.hasColumn(AbsNotesRunner.NotesURL)) {
						action = new Action("Open Notes Client") {
							public void run() {
								Program.launch(rdh.getStringData(
										lastSelectedRow,
										AbsNotesRunner.NotesURL));
							};
						};
						manager.add(action);
					}
					Program notesBrawser = ProgramUtil.getNotesProgram();
					if (notesBrawser != null
							&& rdh.hasColumn(AbsNotesRunner.HttpURL)) {
						action = new Action("Open Browser") {
							public void run() {
								Program.launch(rdh
										.getStringData(lastSelectedRow,
												AbsNotesRunner.HttpURL));
							};
						};
						manager.add(action);
					}
				}
				break;
			}
		}
	}

	@Override
	public boolean hasEditorMenu() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void createEditorContextMenuShow(IMenuManager manager) {
		// TODO Auto-generated method stub

	}

	@Override
	public void createConnectionMenuShow(IMenuManager manager,
			DatabaseType databaseType, final ConnectionProperties prop) {

		String text = String.format("Connect to %s", prop.getDisplayString());
		Action connect = new Action(text,
				ImageUtil.getImageDescriptor(ImageUtil.ACTION_32_CONNECT)) {
			@Override
			public void run() {
				Request request = new Request(SQLOperationType.CONNECT, prop);
				request.addListener(new MyConnectionRequestAdaptor());
				SQLServerThread.putRequest(request);
			}
		};
		connect.setEnabled(!prop.isConnected());
		manager.add(connect);
		text = String.format("Dis Connect to %s", prop.getDisplayString());
		Action dis_connect = new Action(text,
				ImageUtil.getImageDescriptor(ImageUtil.ACTION_33_DISCONNECT)) {
			@Override
			public void run() {
				Request request = new Request(SQLOperationType.CLOSE, prop);
				request.addListener(new MyDisconnectRequestAdaptor());
				SQLServerThread.putRequest(request);
			}
		};
		dis_connect.setEnabled(prop.isConnected());
		manager.add(dis_connect);
		manager.add(new Separator());
		Action connectionDialog = new Action("Open Connection Config Dialog",
				ImageUtil.getImageDescriptor(ImageUtil.ACTION_00_TREE_REFRESH)) {
			@Override
			public void run() {
				treeViewer.openConfigDialog(prop);
			}
		};
		manager.add(connectionDialog);
	}

	@Override
	public void createResourceOfDBMenuShow(final Shell shell,
			IMenuManager manager, DatabaseType databaseType,
			final ConnectionProperties prop,
			final DBResourceTreeSelection selection) {
		if (selection.getFirstDBResource() instanceof IDBSchema
				|| selection.getFirstDBResource() instanceof IDBTable) {
			manager.add(new Action("Database mirroring") {
				@Override
				public void run() {
					for (IDBSchema schema : selection.getSchemaSet(false)) {
						if (schema.getTableOrSystemTables().length == 0) {
							refreshSchemaResources(schema);
						}
						for (IDBTable table : schema.getTableOrSystemTables()) {
							if (table.getColumns().length == 0) {
								refreshTableColumns(table);
							}
						}
					}
					for (IDBTable table : selection.getTableAndViewSet(false)) {
						if (table.getColumns().length == 0) {
							refreshTableColumns(table);
						}
					}
					DefaultMirroringDialog dialog = new DefaultMirroringDialog(
							shell, prop, selection);
					dialog.open();
					v.setInputAdjustDatum(dialog.getMirroringRequest().getRdh());
				}
			});
			manager.add(new Action("Compare to another database") {
				@Override
				public void run() {
					DefaultDatabaseComparingDialog dialog = new DefaultDatabaseComparingDialog(
							shell, prop, selection);
					dialog.open();
				}
			});
			manager.add(new Separator());
		}
	}

	class MyDisconnectRequestAdaptor extends RequestAdaptor {

		@Override
		public void called_done(Request request, SQLOperationType operation,
				final ConnectionProperties properteis, Object o) {
			final ResultSetDataHolder rdh = new ResultSetDataHolder(
					new String[] { "result", "exceptins" });
			Throwable ex = request.getException();
			if (ex == null) {
				rdh.addRow(new String[] { String.valueOf(request.result),
						StringUtil.EMPTY_STRING });
			} else {
				rdh.addRow(new String[] { String.valueOf(request.result),
						ex.getMessage() });
				for (StackTraceElement line : ex.getStackTrace()) {
					rdh.addRow(new String[] { StringUtil.EMPTY_STRING,
							line.toString() });

				}
				Throwable ex2 = ex.getCause();
				if (ex2 != null) {
					Throwable ex3 = ex2.getCause();
					if (ex3 != null) {
						rdh.addRow(new String[] { StringUtil.EMPTY_STRING,
								"    " + ex3.getMessage() });
						for (StackTraceElement line : ex3.getStackTrace()) {
							rdh.addRow(new String[] { StringUtil.EMPTY_STRING,
									"    " + line.toString() });
						}
					}
				}
			}
			display.asyncExec(new Runnable() {
				@Override
				public void run() {
					v.setInputAdjustDatum(rdh);
					rdhViewerConnection = properteis;
					treeViewer.refresh();

					setStatus("DisConnected...");
				}
			});
		}

	}

	class MyConnectionRequestAdaptor extends RequestAdaptor {
		@Override
		public void called_done(Request request, SQLOperationType operation,
				final ConnectionProperties properteis, Object o) {
			final ResultSetDataHolder rdh = new ResultSetDataHolder(
					new String[] { "result", "exceptins" });
			final Throwable ex = request.getException();
			if (ex == null) {
				rdh.addRow(new String[] { String.valueOf(request.result),
						StringUtil.EMPTY_STRING });
			} else {
				rdh.addRow(new String[] { String.valueOf(request.result),
						ex.getMessage() });
				for (StackTraceElement line : ex.getStackTrace()) {
					rdh.addRow(new String[] { StringUtil.EMPTY_STRING,
							line.toString() });

				}
				Throwable ex2 = ex.getCause();
				if (ex2 != null) {
					Throwable ex3 = ex2.getCause();
					if (ex3 != null) {
						rdh.addRow(new String[] { StringUtil.EMPTY_STRING,
								"    " + ex3.getMessage() });
						for (StackTraceElement line : ex3.getStackTrace()) {
							rdh.addRow(new String[] { StringUtil.EMPTY_STRING,
									"    " + line.toString() });
						}
					}
				}
			}
			display.asyncExec(new Runnable() {
				@Override
				public void run() {
					if (ex != null) {
						MessageDialog.openError(null, StringUtil.EMPTY_STRING,
								ex.getMessage());
					}
					rdhViewerConnection = properteis;
					v.setInputAdjustDatum(rdh);
					if (properteis.isConnected()
							&& properteis
									.isCaptureResourceAfterTheConnectProcess()) {
						captureResource(properteis);
					}

					setStatus("Connected...");
				}
			});
		}
	}
}
