/*
 * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
 */
package com.sun.javafx.tk.quantum;

import javafx.application.Platform;
import com.sun.glass.ui.Application;

import java.util.concurrent.Callable;

public final class FxEventLoop {

    private final static class Impl extends AbstractEventLoop {

        private Object nestedEventLoopTkn;
        private int depth;

        @Override
        public void send(final Runnable r) {
            if (Platform.isFxApplicationThread()) {
                r.run();
                return;
            }
            super.send(r);
        }

        @Override
        public <V> V send(final Callable<V> c) {
            if (Platform.isFxApplicationThread()) {
                try {
                    return c.call();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            return super.send(c);
        }

        @Override
        public void start() {
            if (Platform.isFxApplicationThread()) {
                // Don't allow nested nested loops
                assert (depth == 0);

                ++depth;
                try {
                    nestedEventLoopTkn = Application.enterNestedEventLoop();
                } finally {
                    --depth;
                }
            } else {
                Platform.runLater(new Runnable() {

                    @Override
                    public void run() {
                        enterNestedLoop();
                    }
                });
            }
        }

        @Override
        public void stop() {
            if (Platform.isFxApplicationThread()) {
                Application.leaveNestedEventLoop(nestedEventLoopTkn);
                nestedEventLoopTkn = null;
            } else {
                send(new Runnable() {

                    @Override
                    public void run() {
                        leaveNestedLoop();
                    }
                });
            }
        }

        @Override
        protected void schedule(Runnable r) {
            Platform.runLater(r);
        }

        boolean isNestedLoopRunning() {
            assert Platform.isFxApplicationThread();

            return (depth != 0);
        }
    }
    private final static Impl impl = new Impl();

    public static void enterNestedLoop() {
        impl.start();
    }

    public static void leaveNestedLoop() {
        impl.stop();
    }

    public static void sendEvent(final Runnable e) {
        impl.send(e);
    }

    public static <V> V sendEvent(final Callable<V> e) {
        return impl.send(e);
    }

    public static boolean isNestedLoopRunning() {
        return impl.isNestedLoopRunning();
    }
}
