// -*- Mode: vala; indent-tabs-mode: nil; tab-width: 4 -*-
/*-
 * Copyright (c) 2012 Noise Developers (http://launchpad.net/noise)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 * The Noise authors hereby grant permission for non-GPL compatible
 * GStreamer plugins to be used and distributed together with GStreamer
 * and Noise. This permission is above and beyond the permissions granted
 * by the GPL license by which Noise is covered. If you modify this code
 * you may extend this exception to your version of the code, but you are not
 * obligated to do so. If you do not wish to do so, delete this exception
 * statement from your version.
 */

/**
 * A central place for spawning threads.
 *
 * The main purpose of this class is to have a central place to track and control all the
 * threads created by the application, in a thread-safe environment. Second, but not less
 * important, is the ability to re-use existing threads in order to minimize the overhead
 * generated by the creation/destruction of new threads under certain conditions.
 */
public class Noise.Threads {

    public delegate void TaskFunc ();

    /**
     * An object that wraps a TaskFunc delegate.
     *
     * We need this class because delegates with targets cannot be pushed directly into
     * a thread pool, nor used as generic type arguments. This doesn't mean the class is
     * merely a workaround though. Its existence has the bonus of allowing easy tracking
     * of task creation/destruction, and the internal counter exposes the number of tasks
     * that have been processed during the entire execution time of the application.
     */
    private class TaskFuncWrapper : Object {
        public unowned TaskFunc func { get; private set; }
        public uint id { get; private set; }
        private static uint count = 0;

        public TaskFuncWrapper (TaskFunc func) {
            lock (count)
                id = count++;

            debug ("Creating task [%u]", id);
            this.func = func;
        }

        ~TaskFuncWrapper () {
            debug ("~Destroying task [%u]", id);
        }
    }

    /**
     * Maximum number of threads allowed; -1 equals "unlimited".
     */
    private const int MAX_THREADS = -1;

    /**
     * Maximum number of threads that will be kept alive while not used.
     */
    private const int MAX_UNUSED_THREADS = 5;

    private ThreadPool<TaskFuncWrapper>? thread_pool;
    private static Threads? instance;


    private Threads () {
        assert (instance == null); // We only want a single instance

        lock (thread_pool) {
            try {
                thread_pool = new ThreadPool<TaskFuncWrapper>.with_owned_data (
                                                               task_func,
                                                               MAX_THREADS,
                                                               MAX_THREADS > 0);
            } catch (Error err) {
                error ("Couldn't create default thread pool: %s", err.message);
            }

            ThreadPool.set_max_unused_threads (MAX_UNUSED_THREADS);
        }
    }

    /**
     * Adds //task// to be processed on a separate thread. The task function is not
     * owned by the method and should be kept alive by the owner until it is actually
     * called from a different thread.
     */
    public static bool add (TaskFunc task) {
        lock (instance) {
            if (instance == null)
                instance = new Threads ();
        }

        try {
            instance.push_task (task);
        } catch (Error err) {
            critical ("Could not add task: %s", err.message);
            return false;
        }

        return true;
    }

    /**
     * Pushes //task// into the thread pool.
     * @see Noise.Threads.add
     */
    private void push_task (TaskFunc task) throws Error {
        lock (thread_pool) {
            var wrapper = new TaskFuncWrapper (task);
            thread_pool.add ((owned) wrapper);
        }
    }

    /**
     * Called by the thread pool right after preparing a thread. The method is
     * responsible for executing the actual task function.
     */
    private void task_func (owned TaskFuncWrapper wrapper) {
        var id = wrapper.id;
        debug ("-- Dispatching task [%u]", id);
        if (wrapper.func != null) {
            debug ("-- starting [%u]", id);
            wrapper.func ();
            debug ("-- finished [%u]", id);
        }
    }
}