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

import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

public abstract class AbstractEventLoop {

    private Object curCallableValue;

    static abstract class Task implements Runnable {

        private final CountDownLatch latch = new CountDownLatch(1);

        @Override
        public void run() {
            try {
                doRun();
            } finally {
                latch.countDown();
            }
        }

        protected abstract void doRun();

        void await() throws InterruptedException {
            latch.await();
        }
    };

    static final class CallableTask<V> extends Task {

        private V retValue;
        private final Callable<V> c;
        private Exception e;

        CallableTask(final Callable<V> c) {
            this.c = c;
        }

        @Override
        public void doRun() {
            try {
                retValue = c.call();
            } catch (Exception e) {
                this.e = e;
            }
        }

        V getResult() {
            if (e == null) {
                return retValue;
            }
            throw new RuntimeException(e);
        }
    }

    static final class RunnableTask extends Task {

        private final Runnable r;

        RunnableTask(final Runnable r) {
            this.r = r;
        }

        @Override
        public void doRun() {
            r.run();
        }
    }

    public AbstractEventLoop() {
    }

    public void send(final Runnable r) {
        final RunnableTask task = new RunnableTask(r);
        await(task);
    }

    public <V> V send(final Callable<V> c) {
        final CallableTask<V> task = new CallableTask<V>(c);
        await(task);
        return task.getResult();
    }

    protected abstract void schedule(Runnable r);

    public abstract void start();

    public abstract void stop();

    private void await(final Task task) {
        schedule(task);
        try {
            task.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
