/*
 * This program 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 2
 * of the License, or (at your option) any later version.
 *
 * This program 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 this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * See the COPYING file for license information.
 *
 * Guillaume Chazarain <guichaz@yahoo.fr>
 */

/*******************
 * Thread handling *
 *******************/

#include <unistd.h>             /* pipe() */
#include <stdio.h>              /* perror() */
#include <fcntl.h>              /* _O_BINARY for MinGW */

#include "gliv.h"
#include "thread.h"
#include "messages.h"

typedef struct {
    GThreadFunc function;
    gpointer argument;
    gpointer result;
} running_data;

typedef struct {
    GIOChannel *start_read;
    GIOChannel *start_write;
    GIOChannel *end_read;
    GIOChannel *end_write;
    volatile running_data *run;
} thread_data;

static GSList *threads_list = NULL;
G_LOCK_DEFINE_STATIC(threads_list);

/* This is executed in a separate thread. */
static gpointer thread_func(thread_data * data)
{
    gchar buf = '\0';

    for (;;) {
        /* Wait start. */
        g_io_channel_read_chars(data->start_read, &buf, 1, NULL, NULL);

        data->run->result = data->run->function(data->run->argument);

        /* Inform that we have finished. */
        g_io_channel_write_chars(data->end_write, &buf, 1, NULL, NULL);
        g_io_channel_flush(data->end_write, NULL);
    }

    return NULL;
}

/* Create a new thread. */
static thread_data *new_thread(void)
{
    thread_data *thread = g_new(thread_data, 1);
    gint start_pipe[2];
    gint end_pipe[2];
    GError *err = NULL;

    if (pipe(start_pipe) < 0) {
        perror("pipe(start_pipe)");
        goto start_pipe_error;
    }

    if (pipe(end_pipe) < 0) {
        perror("pipe(end_pipe)");
        goto end_pipe_error;
    }

    thread->start_read = g_io_channel_unix_new(start_pipe[0]);
    g_io_channel_set_encoding(thread->start_read, NULL, NULL);

    thread->start_write = g_io_channel_unix_new(start_pipe[1]);
    g_io_channel_set_encoding(thread->start_write, NULL, NULL);

    thread->end_read = g_io_channel_unix_new(end_pipe[0]);
    g_io_channel_set_encoding(thread->end_read, NULL, NULL);

    thread->end_write = g_io_channel_unix_new(end_pipe[1]);
    g_io_channel_set_encoding(thread->end_write, NULL, NULL);

    g_thread_create((GThreadFunc) thread_func, thread, TRUE, &err);
    if (err != NULL) {
        g_printerr("%s\n", err->message);
        g_error_free(err);
        goto thread_error;
    }

    return thread;

  thread_error:
    g_io_channel_shutdown(thread->start_read, FALSE, NULL);
    g_io_channel_shutdown(thread->start_write, FALSE, NULL);
    g_io_channel_shutdown(thread->end_read, FALSE, NULL);
    g_io_channel_shutdown(thread->end_write, FALSE, NULL);

  end_pipe_error:
    close(start_pipe[0]);
    close(start_pipe[1]);

  start_pipe_error:
    return NULL;
}

static thread_data *find_free_thread(void)
{
    GSList *node;
    thread_data *thread = NULL;

    for (node = threads_list; node != NULL; node = node->next) {
        thread_data *node_thread;

        node_thread = node->data;
        if (node_thread->run == NULL) {
            thread = node_thread;
            break;
        }
    }

    if (thread == NULL) {
        thread = new_thread();
        if (thread != NULL)
            threads_list = g_slist_prepend(threads_list, thread);
    }

    return thread;
}

/* Called when a threaded job is finished. */
static gboolean done(GIOChannel * tmp1, GIOCondition tmp2,
                     volatile GThreadFunc * f)
{
    *f = NULL;
    return FALSE;
}

gpointer do_threaded(GThreadFunc f, gpointer arg)
{
    thread_data *thread;
    gpointer result;
    guchar buf = '\0';

    G_LOCK(threads_list);
    thread = find_free_thread();
    if (thread == NULL) {
        G_UNLOCK(threads_list);
        g_printerr(_("Cannot use a thread\n"));
        return f(arg);
    }

    thread->run = g_new(running_data, 1);
    thread->run->function = f;
    thread->run->argument = arg;

    G_UNLOCK(threads_list);

    g_io_add_watch(thread->end_read, G_IO_IN, (GIOFunc) done,
                   (gpointer) & thread->run->function);

    /* Start. */
    g_io_channel_write_chars(thread->start_write, &buf, 1, NULL, NULL);
    g_io_channel_flush(thread->start_write, NULL);

    while (thread->run->function != NULL)
        gtk_main_iteration();

    g_io_channel_read_chars(thread->end_read, &buf, 1, NULL, NULL);
    result = thread->run->result;
    g_free((gpointer) thread->run);
    thread->run = NULL;

    return result;
}
