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


import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IWorkbenchPart;

import zigen.plugin.db.DbPlugin;
import zigen.plugin.db.IStatusChangeListener;
import zigen.plugin.db.core.IDBConfig;
import zigen.plugin.db.ext.jdt.Activator;
import zigen.plugin.db.ui.util.ResourceUtil;

public class SelectionAdapter implements ISelectionListener {

    public void selectionChanged(IWorkbenchPart part, ISelection selection) {
            try {
				if (selection != null && selection instanceof StructuredSelection) {
				    Object obj = ((StructuredSelection) selection).getFirstElement();
				    if (obj != null) {

				        IDBConfig config = null;
				        if (obj instanceof IJavaProject) {
				            IJavaProject iprj = (IJavaProject) obj;
				            IProject prj = iprj.getProject();

				            config = ResourceUtil.getDBConfig(prj);

				        } else if(obj instanceof ICompilationUnit){
				            ICompilationUnit unit = (ICompilationUnit)obj;
				            IProject prj = unit.getJavaProject().getProject();
				            config = ResourceUtil.getDBConfig(prj);

				        }else if(obj instanceof IAdaptable){
				        	IAdaptable adaptable = (IAdaptable)obj;
				        	IFile file = (IFile)adaptable.getAdapter(IResource.class);
				        	if(file != null)
				        	config = ResourceUtil.getDBConfig(file);
				        }


				        /*
				        else if (obj instanceof IResource) {
				            config = ResourceUtil.getDBConfig((IResource) obj);


				        } else if (obj instanceof TreeNode) {
				            config = ((TreeNode) obj).getDbConfig();

				        }
				        */
				        if (config != null){
				            DbPlugin.fireStatusChangeListener(config,IStatusChangeListener.EVT_ChangeDataBase);
				        }
				    }

				}
			} catch (RuntimeException e) {
				Activator.log(e);
			}


    }

}
