package dfatool.views.dialogs;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.window.IShellProvider;
import org.eclipse.swt.SWT;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;

import dfatool.gui.nature.DFAToolNature;
import dfatool.strategy.elements.Configuration;
import dfatool.strategy.graph.CommunicationGraph;
import dfatool.views.DescriptionList;
import dfatool.views.NetworkList;
import dfatool.views.graph.GraphView;

public class ConfigurationDialog extends CreationDialog{

	public ConfigurationDialog(IShellProvider parentShell) {
		super(parentShell);
	}

	@Override
	protected Map<String, Integer> createFields() {
		HashMap<String, Integer> map = new HashMap<String,Integer>();
		map.put("Project name", SWT.SINGLE | SWT.BORDER);
		return map;
	}

	@Override
	protected void okPressed() {
		String projectName = fields.get("Project name").getText();
		IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
		IProject project = root.getProject(projectName);
		try {
			System.out.println("Project name: "+ projectName);
			System.out.println("Project exists: "+ project.exists());
			System.out.println("Project has nature: "+ project.hasNature(DFAToolNature.ID));
			for(String s : project.getDescription().getNatureIds())
				System.out.println(s);
			if(project.exists() && project.hasNature(DFAToolNature.ID)){
				System.out.println("Project configured!");
				Configuration.update(project.getLocation());
				CommunicationGraph.getInstance().reInit();
				IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
				((DescriptionList) page.findView(DescriptionList.ID)).refresh();
				((NetworkList) page.findView(NetworkList.ID)).refresh();
				((GraphView) page.findView(GraphView.ID)).asyncRefresh();
				this.close();
			}else{
				System.out.println("Project not configured!");
				open();
			}
		}catch (Exception e){
			MessageDialog.openError(this.getParentShell(), "Error", e.getMessage());
		}finally{
			this.close();
		}
	}
}
