package com.redhat.ceylon.eclipse.core.launch;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.model.LaunchConfigurationDelegate;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleConstants;
import org.eclipse.ui.console.IConsoleManager;
import org.eclipse.ui.console.MessageConsole;

import com.redhat.ceylon.ant.Ceylonjs;
import com.redhat.ceylon.compiler.js.CeylonRunJsException;
import com.redhat.ceylon.compiler.js.CeylonRunJsTool;
import com.redhat.ceylon.compiler.js.Runner;
import com.redhat.ceylon.eclipse.core.builder.CeylonBuilder;
import com.redhat.ceylon.eclipse.ui.CeylonPlugin;

import static org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME;

public class JsLaunchDelegate extends LaunchConfigurationDelegate {

    private MessageConsole findConsole() {
        ConsolePlugin plugin = ConsolePlugin.getDefault();
        IConsoleManager conman = plugin.getConsoleManager();
        MessageConsole cons = null;
        for (IConsole ccons : conman.getConsoles()) {
            if ("com.redhat.ceylon".equals(ccons.getName())) {
                cons = (MessageConsole)ccons;
                break;
            }
        }
        if (cons == null) {
            cons = new MessageConsole("com.redhat.ceylon", IConsoleConstants.MESSAGE_CONSOLE_TYPE,
                    null, "UTF-8", true);
            conman.addConsoles(new IConsole[]{cons});
        }
        cons.clearConsole();
        return cons;
    }

    @Override
    public void launch(ILaunchConfiguration configuration, String mode,
            ILaunch launch, IProgressMonitor monitor) throws CoreException {

        final IProject proj = ResourcesPlugin.getWorkspace().getRoot().getProject(
                configuration.getAttribute(ICeylonLaunchConfigurationConstants.ATTR_PROJECT_NAME, (String)null));
        if (!CeylonBuilder.compileToJs(proj)) {
            throw new CoreException(new Status(IStatus.ERROR, CeylonPlugin.PLUGIN_ID,
                    "JavaScript compilation is disabled for this project."));
        }
        //Check that JS is enabled for the project
        final String qname = configuration.getAttribute(ATTR_MAIN_TYPE_NAME, "::run");
        final int tipple = qname.indexOf("::");
        final String methname = tipple >= 0 ? qname.substring(tipple+2) : qname;
        final String modname = configuration.getAttribute(ICeylonLaunchConfigurationConstants.ATTR_CEYLON_MODULE, "default");
        final ArrayList<String> repos = new ArrayList<String>();
        //Add system repo
        repos.add(CeylonBuilder.interpolateVariablesInRepositoryPath(CeylonBuilder.getCeylonSystemRepo(proj)));
        //Add project repos
        repos.addAll(CeylonBuilder.getCeylonRepositories(proj));
        repos.add(CeylonBuilder.getCeylonModulesOutputDirectory(proj).getAbsolutePath());
        PrintStream pout = new PrintStream(findConsole().newOutputStream());
        try {
            CeylonRunJsTool runner = new CeylonRunJsTool();
            runner.setRepositories(repos);
            runner.setRun(methname);
            runner.setModuleVersion(modname);
            runner.setOutput(pout);
            runner.run();
        } catch (CeylonRunJsException ex) {
            //Install node.js
            throw new CoreException(new Status(IStatus.ERROR, CeylonPlugin.PLUGIN_ID,
                    ex.getMessage()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new CoreException(new Status(IStatus.ERROR, CeylonPlugin.PLUGIN_ID,
                    e.getClass().getName() + " - " + e.getMessage()));
        } finally {
            pout.close();
        }
    }

}

@@ -45,74 +45,8 @@
 h;%0A%0A
-import java.io.FileNotFoundException;%0Aimport java.io.IOException;%0A
 impo
@@ -69,16 +69,16 @@
 Stream;%0A
+
 import j
@@ -759,47 +759,8 @@
 e;%0A%0A
-import com.redhat.ceylon.ant.Ceylonjs;%0A
 impo
@@ -872,53 +872,8 @@
 ol;%0A
-import com.redhat.ceylon.compiler.js.Runner;%0A
 impo
@@ -3112,24 +3112,184 @@
 ies(proj));%0A
+        //Add referenced project repos%0A        repos.addAll(CeylonBuilder.getReferencedProjectsOutputRepositories(proj));%0A        //And finally the output repo%0A
         repo
@@ -3679,16 +3679,51 @@
 (pout);%0A
+            runner.setDebug(true);%0A
         
@@ -3892,32 +3892,32 @@
 ugin.PLUGIN_ID,%0A
-
                 
@@ -3931,32 +3931,953 @@
 getMessage()));%0A
+        %7D catch (RuntimeException ex) %7B%0A            ex.printStackTrace();%0A            if (proj.getReferencedProjects() != null && proj.getReferencedProjects().length %3E 0) %7B%0A                boolean all = true;%0A                for (IProject dep : proj.getReferencedProjects()) %7B%0A                    all &= CeylonBuilder.compileToJs(dep);%0A                %7D%0A                if (!all) %7B%0A                    throw new CoreException(new Status(IStatus.ERROR, CeylonPlugin.PLUGIN_ID,%0A                            %22Not all the referenced projects compile to JavaScript, which may be causing this error:%22%0A                            + ex.getClass().getName() + %22 - %22 + ex.getMessage()));%0A                %7D%0A            %7D%0A            throw new CoreException(new Status(IStatus.ERROR, CeylonPlugin.PLUGIN_ID,%0A                    %22Node.js exited abnormally: %22 + %0A                    ex.getClass().getName() + %22 - %22 + ex.getMessage()));%0A
         %7D catch 

Fix #433 and show helpful message if js is not enabled for all deps