/*
 * Created on 2004-08-16
 *
 * Part of the Symbian development plug-in for Eclipse
 * Copyright (C) Mikołaj Zalewski, 2004
 */
package pl.zalewski.mikolaj.symbdev;

import java.io.File;
import java.io.IOException;
import java.util.Properties;

import org.eclipse.cdt.utils.spawner.EnvironmentReader;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;

import pl.zalewski.mikolaj.symbdev.properties.ProjectProperties;

/**
 * @author mikolaj
 *
 * This class provides helper function to setup environment and
 * working directory for Symbian build commands
 */
public class SymbianCommandHelper
{
    public static IPath getWorkingDirectoryPath(IProject prj) throws CoreException
    {
        IPath prjPath=prj.getLocation();
        Path p=new Path(ProjectProperties.getBuildPath(prj));
        return prjPath.append(p);
    }

    /**
     * Returns the working directory for the build commands 
     * @param prj The Symbian OS project 
     * @return The path (in DOS format - with '\') of the working directory. By
     * default &lt;project root&gt;\group. The path is not guaranteed to exist
     * @throws CoreException some problems, e.g. invalid path
     */
    public static String getWorkingDirectory(IProject prj) throws CoreException
    {
        return getWorkingDirectoryPath(prj).toOSString();
    }
    
    /**
     * Returns the working directory for the build commands. In case of error
     * a message box is displayed. If the directory doesn't exists and askCreate is
     * true, the user is aksed if it should be created 
     * @param prj The Symbian OS project 
     * @param shell The parent shell for the dialogs
     * @param askCreate Should the metod ask if the directory should be created 
     * @return The path (in DOS format - with '\') of the working directory or
     * null if directory doesn't exist. By default &lt;project root&gt;\group 
     */
    public static String getWorkingDirectory(IProject prj, Shell shell, boolean askCreate)
    {
        IPath path;
        try
        {
            path=getWorkingDirectoryPath(prj);
        }
        catch (CoreException e)
        {
            ErrorDialog.openError(shell, SymbdevPlugin.MESSAGE_TITLE,
                    "Couldn't retrieve build path", e.getStatus());
            return null;
        }
        
        File f=new File(path.toString());
        if (f.exists())
        {
            if (!f.isDirectory())
            {
                MessageDialog.openError(shell, SymbdevPlugin.MESSAGE_TITLE,
                        "The path provided in Project > Properties > Symbian "+
                        "OS Development points to a file instead of a directory");
                return null;
            }
        } else if (askCreate)
        {
            if (!MessageDialog.openQuestion(shell, SymbdevPlugin.MESSAGE_TITLE,
                    "Build directory as provided in Project > Properties > "+
                    "SymbianOS Development doesn't exists. Create?"))
                return null;
            if (!f.mkdirs())
            {
                MessageDialog.openError(shell, SymbdevPlugin.MESSAGE_TITLE,
                        "Failed to create the directory");
                return null;
            }
            try {
                prj.refreshLocal(IResource.DEPTH_INFINITE, null);
            }
            catch (CoreException e)
            {
                e.printStackTrace();
            }
        } else        // !f.exists && !askCreate
            return null;
        
        return path.toOSString();
    }
    
    public static String getOSShell(boolean useSystemShell)
    {
        if (!useSystemShell)
        {
            if (internalShell!=null)
                return internalShell;
            try {
                internalShell=SymbdevPlugin.getDefault().getFile(SymbdevPlugin.CMD_PATH).toOSString();
                if (internalShell!=null)
                    return internalShell;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        if (osShell==null)
        {
    		Properties env=EnvironmentReader.getEnvVars();
    		osShell=env.getProperty("COMSPEC", "cmd.exe");
        }
        return osShell;        
    }
    
    public static String getOSShell()
    {
        return getOSShell(true);
    }
    
    static String osShell;
    static String internalShell;
    
    public static String[] buildEnvironment(IProject prj) throws CoreException
    {
        return buildEnvironment(prj, true);
    }
    
    public static String[] buildEnvironment(IProject prj, boolean systemShell) throws CoreException
    {
        Win32ToolEntry tool=ProjectProperties.getWin32Tool(prj);
        SymbianSDKEntry sdk=ProjectProperties.getSymbianSDK(prj);

		Properties env=EnvironmentReader.getEnvVars();        
		tool.alterEnvironment(env);
		sdk.alterEnvironment(env);
		
		if (!systemShell)
		{
		    String oldShell=env.getProperty("COMSPEC");
		    String newpath=null;
		    try {
		        newpath=SymbdevPlugin.getDefault().getFile(SymbdevPlugin.CMD_PATH).toOSString();
            } catch (IOException e) {
                e.printStackTrace();
            }
	        if (newpath!=null)
	        {
	            env.setProperty("COMSPEC", newpath);
	            env.setProperty("SHELL", newpath);
	        }            
		}
        
        return SymbdevPlugin.envPropertiesToArray(env);
    }
}
