
package org.apache.sling.ide.eclipse.ui.internal.console;

import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleFactory;
import org.eclipse.ui.console.IConsoleManager;
import org.eclipse.ui.console.MessageConsole;

public class SlingConsoleFactory implements IConsoleFactory {

    public static final String CONSOLE_NAME = "Sling console";

    private MessageConsole console;

    public static MessageConsole getConsole() {
        // TODO not the right place, should converge with initConsole

        for (IConsole console : ConsolePlugin.getDefault().getConsoleManager().getConsoles()) {
            if (console.getName().equals(CONSOLE_NAME)) {
                return (MessageConsole) console;
            }
        }

        return null;
    }

    @Override
    public void openConsole() {

        IConsoleManager consoleManager = ConsolePlugin.getDefault().getConsoleManager();

        initConsole(consoleManager);

        consoleManager.showConsoleView(console);
    }

    private void initConsole(IConsoleManager consoleManager) {

        if (console == null) {
            console = new MessageConsole(CONSOLE_NAME, null);
            consoleManager.addConsoles(new IConsole[] { console });
        }
    }

}
