// Copyright 2014-2025 Jesper Larsson
//
// This file is part of Klipspringer, <https://klipspringer.avadeaux.net/>
//
// Klipspringer is free software: you can redistribute it and/or modify it under the terms of the
// GNU General Public License as published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// Klipspringer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
// even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with Klipspringer. If
// not, see <https://www.gnu.org/licenses/>.

package net.avadeaux.klipspringer;

import java.util.*;
import java.util.concurrent.Executor;

public class QueueExecutor implements Executor {
    private static class Runner implements Runnable {
        private boolean exit = false;
        private Queue<Runnable> queue = new LinkedList<Runnable>();

        synchronized void exit() {
            // Half a second delay to allow first stream to be started.
            for (long t = System.currentTimeMillis(), e = t+500; t < e; t = System.currentTimeMillis()) {
                try { wait(e-t); } catch (InterruptedException ex) { }
            }
            exit = true;
            notifyAll();
        }

        synchronized void enqueue(Runnable r) {
            queue.add(r);
            notifyAll();
        }

        public synchronized void run() {
            while (true) {
                while (!exit && queue.isEmpty()) {
                    try { wait(); } catch (InterruptedException e) { }
                }
                if (exit) { return; }
                try {
                    queue.remove().run();
                } catch (Exception ex) {
                    if (System.getProperty("klipspringer.debug") != null) { ex.printStackTrace(); }
                    return;
                }
            }
        }
    }

    private final Runner runner = new Runner();
    private final Thread thread;

    public QueueExecutor(String threadName) {
        thread = new Thread(runner, threadName);
        thread.start();
    }

    public void execute(Runnable r) { runner.enqueue(r); }
    public void exit() { runner.exit(); }
}
