package zigen.plugin.db.ext.s2jdbc.ui;

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

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jface.viewers.DecoratingLabelProvider;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.ui.dialogs.SelectionDialog;
import org.eclipse.ui.model.WorkbenchLabelProvider;

import zigen.plugin.db.ext.s2jdbc.Activator;

public class JavaSourceSelectDialog extends SelectionDialog {
	
	private TreeViewer treeViewer;
	
	private Tree tree;
	
	private IAdaptable root;
	
	private String projectName;
	
	public JavaSourceSelectDialog(Shell parentShell, IAdaptable root, String message, String projectName) {
		super(parentShell);
		setTitle("リソースの選択");
		this.root = root;
		if (message != null) {
			setMessage(message);
		} else {
			setMessage("リソースを選択します。");
		}
		setShellStyle(getShellStyle() | SWT.RESIZE);
		this.projectName = projectName;
	}
	
	private void checkInitialSelections() {
		// ダイアログを呼んだヤツが、あらかじめSelectionをセットしている場合
		// の処理を記述する。
		Iterator itemsToCheck = getInitialElementSelections().iterator();
		
		while (itemsToCheck.hasNext()) {
			IResource currentElement = (IResource) itemsToCheck.next();
			
			if (currentElement.getType() == IResource.FILE) {
				// selectionGroup.initialCheckListItem(currentElement);
			} else {
				// selectionGroup.initialCheckTreeItem(currentElement);
			}
		}
	}
	
	protected void configureShell(Shell shell) {
		super.configureShell(shell);
	}
	
	public void create() {
		super.create();
		initializeDialog();
	}
	
	/*
	 * (non-Javadoc) Method declared on Dialog.
	 */
	protected Control createDialogArea(Composite parent) {
		Composite composite = (Composite) super.createDialogArea(parent);
		
		createMessageArea(composite);
		
		treeViewer = new TreeViewer(composite, SWT.BORDER);
		tree = treeViewer.getTree();
		tree.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
		
		treeViewer.setContentProvider(new TreeContentProvider());
		treeViewer.setLabelProvider(new DecoratingLabelProvider(new WorkbenchLabelProvider(), Activator.getDefault().getWorkbench().getDecoratorManager().getLabelDecorator()));
		
		treeViewer.addFilter(new ViewerFilter() {
			
			@Override
			public boolean select(Viewer viewer, Object parentElement, Object element) {
				
				if (element instanceof IProject) {
					IProject project = (IProject) element;
					if (!project.isAccessible()) {
						return false;
					}
				} else if (element instanceof IFile) {
					IFile file = (IFile) element;
					if (!"java".equals(file.getFileExtension())) {
						return false;
					}
					
				} else if (element instanceof IFolder) {
					// if (!(element instanceof IPackageFragment)) {
					// return false;
					// }
					IFolder f = (IFolder) element;
					IPackageFragment pf = (IPackageFragment) f.getAdapter(IPackageFragment.class);
				}
				
				return true;
			}
		});
		
		// treeViewer.setInput(((IWorkspaceRoot) root).getProjects());
		treeViewer.setInput(((IWorkspaceRoot) root).getProject(projectName));
		
		treeViewer.addSelectionChangedListener(listener);
		
		return composite;
	}
	
	// /**
	// * Returns a content provider for <code>IResource</code>s that returns
	// * only children of the given resource type.
	// */
	// private ITreeContentProvider getResourceProvider(final int resourceType)
	// {
	// return new WorkbenchContentProvider() {
	// public Object[] getChildren(Object o) {
	// if (o instanceof IContainer) {
	// IResource[] members = null;
	// try {
	// members = ((IContainer) o).members();
	// } catch (CoreException e) {
	// // just return an empty set of children
	// return new Object[0];
	// }
	//
	// // filter out the desired resource types
	// ArrayList results = new ArrayList();
	// for (int i = 0; i < members.length; i++) {
	// // And the test bits with the resource types to see if
	// // they are what we want
	// if ((members[i].getType() & resourceType) > 0) {
	// results.add(members[i]);
	// }
	// }
	// return results.toArray();
	// }
	// // input element case
	// if (o instanceof ArrayList) {
	// return ((ArrayList) o).toArray();
	// }
	// return new Object[0];
	// }
	// };
	// }
	
	/**
	 * Initializes this dialog's controls.
	 */
	private void initializeDialog() {
		// selectionGroup.addCheckStateListener(new ICheckStateListener() {
		// public void checkStateChanged(CheckStateChangedEvent event) {
		// getOkButton().setEnabled(
		// selectionGroup.getCheckedElementCount() > 0);
		// }
		// });
		
		if (getInitialElementSelections().isEmpty()) {
			getOkButton().setEnabled(false);
		} else {
			checkInitialSelections();
		}
	}
	
	/**
	 * The <code>ResourceSelectionDialog</code> implementation of this <code>Dialog</code> method builds a list of the selected resources for later retrieval by the client and closes this dialog.
	 */
	protected void okPressed() {
		IStructuredSelection selection = (IStructuredSelection) treeViewer.getSelection();
		Object firstElement = selection.getFirstElement();
		List list = new ArrayList();
		list.add(firstElement);
		setResult(list);
		super.okPressed();
		
	}
	
	class TreeContentProvider implements IStructuredContentProvider, ITreeContentProvider {
		
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {}
		
		public void dispose() {}
		
		public Object[] getElements(Object inputElement) {
			return getChildren(inputElement);
		}
		
		public Object[] getChildren(Object parentElement) {
			if (parentElement instanceof IProject[]) {
				IProject[] projects = (IProject[]) parentElement;
				return projects;
			}
			
			if (parentElement instanceof IContainer) {
				try {
					final IContainer container = (IContainer) parentElement;
					if (container.isAccessible()) {
						return container.members();
					}
				} catch (CoreException e) {
					e.printStackTrace();
				}
			}
			return new Object[0];
		}
		
		public Object getParent(Object element) {
			return null;
		}
		
		public boolean hasChildren(Object element) {
			return getChildren(element).length > 0;
		}
	}
	
	private ISelectionChangedListener listener = new ISelectionChangedListener() {
		
		public void selectionChanged(SelectionChangedEvent event) {
			
			IStructuredSelection sselection = (IStructuredSelection) event.getSelection();
			IResource firstElement = (IResource) sselection.getFirstElement();
			if (firstElement.getType() == IResource.FILE) {
				getOkButton().setEnabled(true);
			} else {
				getOkButton().setEnabled(false);
			}
		}
		
	};
	
}
