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

import java.util.LinkedList;

import org.eclipse.cdt.ui.CElementLabelProvider;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.ui.AbstractLaunchConfigurationTab;
import org.eclipse.debug.ui.ILaunchConfigurationDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;

import pl.zalewski.mikolaj.symbdev.SymbdevPlugin;
import pl.zalewski.mikolaj.symbdev.SymbianPrjNature;
import pl.zalewski.mikolaj.symbdev.skins.SkinEntry;
import pl.zalewski.mikolaj.symbdev.skins.SkinManager;
import pl.zalewski.mikolaj.symbdev.widgets.SkinCombo;

/**
 * @author mikolaj
 *
 * The first tab of the launch configuration
 */
public class SymbianMainTab extends AbstractLaunchConfigurationTab {

    public SymbianMainTab() {
        super();
        red=new Color(Display.getCurrent(), 255, 0, 0);
        black=new Color(Display.getCurrent(), 0, 0, 0);
    }

    Color red;
    Color black;
    public ILaunchConfigurationDialog fLaunchConfigurationDialog;

	private void addSeparator(Composite parent) {
		Label separator = new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL);
		GridData gridData = new GridData();
		gridData.horizontalAlignment = GridData.FILL;
		gridData.horizontalSpan=3;
		gridData.grabExcessHorizontalSpace = true;
		separator.setLayoutData(gridData);
	}
    
    /* (non-Javadoc)
     * @see org.eclipse.debug.ui.ILaunchConfigurationTab#createControl(org.eclipse.swt.widgets.Composite)
     */
    public void createControl(Composite parent) {
        Composite panel=new Composite(parent, SWT.NONE);
        GridLayout layout=new GridLayout(3, false);
        panel.setLayout(layout);
        GridData data;
        setControl(panel);
        
        Label l=new Label(panel, SWT.WRAP);
        l.setText("This launch configuration will launch the Symbian emulator\nassociated with the selected project");
        data=new GridData(GridData.FILL_HORIZONTAL);
        data.horizontalSpan=3;
        l.setLayoutData(data);
        
        l=new Label(panel, SWT.NONE);
        l.setText("Project Name: ");
        
        projectNameLabel=new Text(panel, SWT.READ_ONLY|SWT.WRAP);
        projectNameLabel.setText("");
        data=new GridData(GridData.FILL_HORIZONTAL);
        projectNameLabel.setLayoutData(data);
        projectNameLabel.setBackground(panel.getBackground());
        
        Button b=new Button(panel, SWT.PUSH);
        b.setText("Change...");
        b.addSelectionListener(new SelectionListener() {
            public void widgetDefaultSelected(SelectionEvent e) { event(); }
            public void widgetSelected(SelectionEvent e) { event(); }
            void event() { prjChange(); }
        });
    
        addSeparator(panel);
        
        l=new Label(panel, SWT.NONE);
        l.setText("Emulator skin:");
        
        fSkinCombo=new SkinCombo(panel, SWT.NONE);
        data=new GridData(GridData.FILL_HORIZONTAL);
        data.horizontalSpan=2;
        fSkinCombo.getComboBox().setLayoutData(data);
        fSkinCombo.getComboBox().addSelectionListener(new SelectionListener() {
            public void widgetDefaultSelected(SelectionEvent e) { event(); }
            public void widgetSelected(SelectionEvent e) { event(); }
            void event() { fLaunchConfigurationDialog.updateButtons(); }
        });
        
        l=new Label(panel, SWT.NONE);
        l.setText("Note: Changing the skin only changes the phone image. To "+
                  "emulate the behaviour of the system\nlibraries, use the SDK "+
                  "appropriate for the phone");
        data=new GridData(GridData.FILL_HORIZONTAL);
        data.horizontalSpan=3;
        l.setLayoutData(data);
    }
    
    protected void updateProjectName()
    {
        if (projectName!=null)
        {
            projectNameLabel.setText(projectName);
            projectNameLabel.setForeground(black);
        } else
        {
            projectNameLabel.setText("(not set yet)");
            projectNameLabel.setForeground(red);
        }
    }
    
    protected void prjChange()
    {
        IProject project=chooseSymbProject();
        if (project!=null)
        {
            projectName=project.getName();
            updateProjectName();
            fLaunchConfigurationDialog.updateButtons();
        }
    }
    
	protected IProject chooseSymbProject() {
		try {
			IProject[] projects=ResourcesPlugin.getWorkspace().getRoot().getProjects();
			LinkedList symbianProjects=new LinkedList();
			for (int i=0; i<projects.length; i++)
			{
			    if ((projects[i].isOpen() && projects[i].hasNature(SymbianPrjNature.NATURE_ID))
			            || projects[i].getName().equals(projectName))
			        symbianProjects.addLast(projects[i]);
			}
			projects=(IProject[])symbianProjects.toArray(new IProject[symbianProjects.size()]);

			ILabelProvider labelProvider = new CElementLabelProvider();
			ElementListSelectionDialog dialog = new ElementListSelectionDialog(getShell(), labelProvider);
			dialog.setTitle("Select Project");
			dialog.setMessage("Choose the project to run");
			dialog.setElements(projects);

			IProject projectProp = SymbianLaunchConfigurationDelegate.getSymbianProjectByName(projectName);
			if (projectProp != null) {
				dialog.setInitialSelections(new Object[]{projectProp});
			}
			if (dialog.open() == Window.OK) {
				return (IProject)dialog.getFirstResult();
			}
		} catch (CoreException e) {
			MessageDialog.openError(getShell(), SymbdevPlugin.MESSAGE_TITLE, "Launch UI internal error");
			SymbdevPlugin.getDefault().getLog().log(e.getStatus());
		}
		return null;
	}
	
	public void setLaunchConfigurationDialog(ILaunchConfigurationDialog dialog) {
		fLaunchConfigurationDialog = dialog;
	}
	
    

    /* (non-Javadoc)
     * @see org.eclipse.debug.ui.ILaunchConfigurationTab#setDefaults(org.eclipse.debug.core.ILaunchConfigurationWorkingCopy)
     */
    public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
        SymbianLaunchConfigurationDelegate.setEmulatorSkinId(configuration, null);
    }

    /* (non-Javadoc)
     * @see org.eclipse.debug.ui.ILaunchConfigurationTab#initializeFrom(org.eclipse.debug.core.ILaunchConfiguration)
     */
    public void initializeFrom(ILaunchConfiguration configuration) {
        conf=configuration;
        try {
            projectName=SymbianLaunchConfigurationDelegate.getProjectName(configuration);
            String skinid=SymbianLaunchConfigurationDelegate.getEmulatorSkinId(configuration);
            SkinEntry entry=SkinManager.getDefault().getEntry(skinid);
            fSkinCombo.setResult(entry);
        }
        catch (CoreException e)
        {
            e.printStackTrace();
        }
        updateProjectName();
    }

    /* (non-Javadoc)
     * @see org.eclipse.debug.ui.ILaunchConfigurationTab#performApply(org.eclipse.debug.core.ILaunchConfigurationWorkingCopy)
     */
    public void performApply(ILaunchConfigurationWorkingCopy configuration) {
        SymbianLaunchConfigurationDelegate.setProjectName(configuration, projectName);
        SymbianLaunchConfigurationDelegate.setEmulatorSkinId(configuration, fSkinCombo.getResult().getId());
    }

    /* (non-Javadoc)
     * @see org.eclipse.debug.ui.ILaunchConfigurationTab#getName()
     */
    public String getName() {
        return "General";
    }
    
    /* (non-Javadoc)
     * @see org.eclipse.debug.ui.ILaunchConfigurationTab#isValid(org.eclipse.debug.core.ILaunchConfiguration)
     */
    public boolean isValid(ILaunchConfiguration launchConfig) {
        setErrorMessage(null);
        
        if (projectName==null)
        {
            setErrorMessage("Project not set");
            return false;
        }
        
        return true;
    }
    ILaunchConfiguration conf;
    Text projectNameLabel;
    String projectName;
    SkinCombo fSkinCombo;
}
