import hiro.yoshioka.sdh.CDHTableViewer;
import hiro.yoshioka.sdh.CSVRecordDataHolder;
import hiro.yoshioka.sdh.ResultSetDataHolder;
import hiro.yoshioka.sql.engine.Request;
import hiro.yoshioka.sql.engine.RequestAdaptor;
import hiro.yoshioka.sql.engine.GettingResourceRequest;
import hiro.yoshioka.sql.engine.SQLOperationType;
import hiro.yoshioka.sql.engine.SQLServerThread;
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.view.DBResourceCompositeMaker;
import hiro.yoshioka.sql.resource.view.DBResourceTreeViewer;
import hiro.yoshioka.sql.resource.view.IDBResourceTreeViewerListener;
import hiro.yoshioka.sql.util.SelectTableDialog;
import hiro.yoshioka.util.CSVUtil;
import hiro.yoshioka.util.ImageUtil;
import hiro.yoshioka.util.StringUtil;

import java.io.File;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class MongoTest {
	Display display;
	static SQLServerThread server;
	DBResourceTreeViewer treeViewer;
	Text treeSearchText;
	CDHTableViewer v;

	public static void main(String[] args) {
		new MongoTest().doWork();
	}

	private void doWork() {

		server = SQLServerThread.getSQLServer();
		File configDir = new File("config");
		System.out.println("dir=" + configDir.mkdir());
		server.init(configDir);

		display = new Display();

		final Shell shell = new Shell(display);
		Composite top = new Composite(shell, SWT.NONE);
		top.setLayout(new FillLayout(SWT.HORIZONTAL));
		shell.setLayout(new GridLayout(2, false));
		top.setLayoutData(new GridData(GridData.FILL_BOTH));

		DBResourceCompositeMaker maker = DBResourceCompositeMaker
				.getInstance(false);
		maker.createControl(top);
		treeViewer = maker.getTreeViewer();
		treeSearchText = maker.getSearchText();
		v = new CDHTableViewer(top);
		treeViewer
				.addDBResourceTreeViewerListener(new IDBResourceTreeViewerListener() {
					@Override
					public void fireDoubleClick(
							ConnectionProperties connectionProperties,
							Object selection) {
						if (selection instanceof ConnectionProperties) {
							connect(connectionProperties);
						} else if (selection instanceof IDBTable) {
							SelectTableDialog dialog = new SelectTableDialog(
									connectionProperties, display
											.getActiveShell(),
									(IDBTable) selection, null);
							if (dialog.open() == SelectTableDialog.OK) {
								System.out.println("return o.k.");
							}
							// final TransactionRequest request = new
							// TransactionRequest(
							// SQLOperationType.SELECT_ALL,
							// connectionProperties, (IDBTable) selection);
							// request.addListener(treeViewer);
							// server.putRequest(request);
							// request.addListener(new RequestAdaptor() {
							// @Override
							// public void called_done(
							// SQLOperationType operation,
							// ConnectionProperties properteis,
							// final Object o) {
							// // final ResultSetDataHolder rdh =
							// display.asyncExec(new Runnable() {
							// @Override
							// public void run() {
							// v.setInputAdjustArea((CSVRecordDataHolder) o);
							// }
							// });
							// }
							// });
						}
					}

					@Override
					public void fireSelectionChanged(
							ConnectionProperties connectionProperties,
							Object selection) {
						// TODO Auto-generated method stub

					}
				});

		Composite btnPanel = new Composite(shell, SWT.BOTTOM);
		btnPanel.setLayout(new FillLayout(SWT.VERTICAL));

		Button delBtn = new Button(btnPanel, SWT.BORDER);
		delBtn.setText("1. connect");
		treeViewer.setInput(server.getConnectionSet());
		// delBtn.addSelectionListener(new SelectionAdapter() {
		// @Override
		// public void widgetSelected(SelectionEvent e) {
		// connect();
		// }
		// });

		Button insBtn = new Button(btnPanel, SWT.BORDER);
		insBtn.setText("2. show colletions");
		insBtn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				GettingResourceRequest request = new GettingResourceRequest(
						treeViewer.getLatestSelectedConnectionProperties());
				SQLServerThread.putRequest(request);
				request.addListener(treeViewer);
				request.addListener(new RequestAdaptor() {
					@Override
					public void beginTask(String taskName, int row) {
						System.out
								.println("begin[" + taskName + "] row=" + row);
					}

					@Override
					public void called_done(Request request,
							SQLOperationType operation,
							ConnectionProperties properteis, Object o) {
						System.out.println("done");
						DBRoot root = SQLServerThread
								.getSQLServer()
								.getTransactionSQL(
										treeViewer
												.getLatestSelectedConnectionProperties())
								.getRoot();
						System.out.println("root=" + root);
						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() {
								v.setInputAdjustArea(rdh);
							}
						});
					}
				});

			}
		});

		Button delSave = new Button(btnPanel, SWT.BORDER);
		delSave.setText("save");
		delSave.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				CSVRecordDataHolder rdh = v.getCDH();
				rdh.saveCSV(new File("hoge.csv"), "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));

		shell.setSize(800, 480);
		shell.open();

		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		server.dispose();
		display.dispose();

	}

	private void connect(ConnectionProperties connectionProperties) {
		final Request request = new Request(SQLOperationType.CONNECT,
				connectionProperties);
		request.addListener(treeViewer);
		server.putRequest(request);
		request.addListener(new RequestAdaptor() {
			@Override
			public void called_done(Request request,
					SQLOperationType operation,
					ConnectionProperties properteis, Object o) {
				final ResultSetDataHolder rdh = new ResultSetDataHolder(
						new String[] { "result", "exceptins" });
				if (request.getException() == null) {
					rdh.addRow(new String[] { String.valueOf(request.result),
							StringUtil.EMPTY_STRING });
				} else {
					rdh.addRow(new String[] {
							String.valueOf(request.result),
							StringUtil.getStackTraceString(request
									.getException()) });
				}
				display.asyncExec(new Runnable() {
					@Override
					public void run() {
						v.setInputAdjustArea(rdh);
					}
				});
			}
		});

	}

}
