package dfatool.gui.wizard;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;

import dfatool.gui.nature.DFAToolNature;
import dfatool.strategy.elements.Configuration;
import dfatool.strategy.elements.Description;
import dfatool.strategy.elements.Network;


public class ToolWizard extends Wizard implements INewWizard{

	CreationPage creation;
	IProject project;
	
	public ToolWizard() {
		super();
		setNeedsProgressMonitor(true);
	}
	
	@Override
	public void addPages() {
		creation = new CreationPage();
		addPage(creation);
	}
	
	@Override
	public boolean performFinish() {
		// TODO Auto-generated method stub
		 createProject();
		 createFiles();
		 Configuration.update(project.getLocation());
		return true;
	}

	private void createFiles() {
		try {
			createFile("network.dfa");
			createFile("channels.dfa");
			createFile("vars.dfa");
			createFile("datatypes.dfa");
			createFile("atoms.dfa");
			createFolder("FDR_Scripts");
			createFolder("FDR_Logs");
		} catch (CoreException  e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void createFile(String name) throws CoreException {
		IFile file = project.getFile(name);
		ByteArrayInputStream stream = new ByteArrayInputStream("<?xml version=\"1.0\" ?><root></root>".getBytes());
		file.create(stream, true, null);
	}
	
	private void createFolder(String name) throws CoreException {
		IFolder folder = project.getFolder(name);
		folder.create(false, true, null);
	}
	
	

	private boolean createProject() {
		IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
		project = root.getProject(creation.getName());
		boolean success = false;
		 try {
			 if(!project.exists()){
				success = true;
				project.create(new NullProgressMonitor());
				project.open(new NullProgressMonitor());
				IProjectDescription description = project.getDescription();
				String[] natures = {DFAToolNature.ID};
				description.setNatureIds(natures);
				project.setDescription(description, new NullProgressMonitor());
			 }
		} catch (CoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return success;
	}
	

	@Override
	public void init(IWorkbench workbench, IStructuredSelection selection) {
	}

}
