/* ====================================================================
 * FTD4Linux Software License, Version 1.0
 *
 * Copyright (c) 2000-2004 The FTD4Linux Development Team.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        FTD4Linux Development Team (http://www.ftd4linux.2y.net/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "FTD" and "FTD4Linux" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact alguno@ftd4linux.2y.net.
 *
 * 5. Products derived from this software may not be called "FTD4Linux",
 *    nor may "FTD4Linux" appear in their name, without prior written
 *    permission of the FTD4Linux Development Team.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE FTD4LINUX DEVELOPMENT TEAM OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include "ftd4linux.h"
#include "ftd_app_core.h"
#include "ftd_events.h"
#include "ftd_event.h"

struct _eventinfo_fetch_data
{
    int eventid;

    char *errmsg;
    FtdErrorCode retval;

    void (*cb) (FtdErrorCode, int, char *, gpointer);
    gpointer data;
};

static gboolean
eventinfo_exec_cb(gpointer data)
{
    struct _eventinfo_fetch_data *fetch_data = (struct _eventinfo_fetch_data *) data;

    fetch_data->cb(fetch_data->retval, fetch_data->eventid, fetch_data->errmsg, fetch_data->data);
    g_free(fetch_data);

    return FALSE;
}

static gpointer
eventinfo_fetch_func(gpointer data)
{
    struct _eventinfo_fetch_data *fetch_data = (struct _eventinfo_fetch_data *) data;

    fetch_data->retval = ftd_eventinfo_fetch(fetch_data->eventid, &fetch_data->errmsg);

    g_idle_add(eventinfo_exec_cb, data);

    return NULL;
}

/**
 * Haalt de gegevens van een event op van de FTD servers.
 * Dit zijn met name de verdere gegevens, zoals aankondiging en forum.
 * Dit ophalen gebeurt in een aparte thread. Zodra het ophalen gelukt
 * (of mislukt) is, zal de callback functie aangeroepen worden
 *
 * @arg     eventid     Het FTD-nummer van het event.
 * @arg     cb          Callback functie
 * @arg     data        Pointer naar data om mee te geven aan de callback functie
 *
 */
void
ftd_eventinfo_fetch_async(int eventid, void (*cb) (FtdErrorCode, int, char *, gpointer), gpointer data)
{
    GThread *thread;
    GError *err = NULL;
    struct _eventinfo_fetch_data *fetch_data;

    g_assert(cb);

    fetch_data = g_malloc0(sizeof(struct _eventinfo_fetch_data));

    fetch_data->eventid = eventid;
    fetch_data->cb = cb;
    fetch_data->data = data;

    thread = g_thread_create(eventinfo_fetch_func, fetch_data, FALSE, &err);
    if (!thread) {
        cb(ERROR_UNKNOWN, eventid, err->message, data);
    }
}

/**
 * Haalt de gegevens van een event op van de FTD servers.
 * Dit zijn met name de verdere gegevens, zoals aankondiging en forum.
 *
 * @arg     eventid     Het FTD-nummer van het event.
 * @arg     errmsg      Een eventuele foutmelding van de server zal hier in gezet worden.
 *
 * @return     Een code die aangeeft of de eventinfo goed was ontvangen.
 */
FtdErrorCode
ftd_eventinfo_fetch(int eventid, char **errmsg)
{
    FtdList     *params = NULL;
    FtdEvent    *event;
    char         postnummer[10];
    FtdString   *uitvoer;
    int          retval;
    FtdEvent    *eventInfo;

    event = ftd_eventlist_lookup_id(core->eventlist, eventid);
    if (!event) {
        /* Probeer de eventinfo opnieuw op te halen van de FTD server */
        event = ftd_eventinfo_findpost(eventid);

        if (!event) {
            return ERROR_NOT_ON_SERVER;
        }
    }

    snprintf(postnummer, sizeof(postnummer), "%i", eventid);
    params = ftd_list_append(params, ftd_http_parameter_new("id", postnummer));

    retval = ftd_http_curl_execute(FTD_URL_POSTS, params, TRUE, &uitvoer, TRUE, NULL, TRUE);

    ftd_http_parameter_free_all( params );
    if (retval != ERROR_NONE) {
        if (retval == ERROR_MSG) {
            *errmsg = g_strdup(ftd_string_value(uitvoer));
        } else {
            *errmsg = NULL;
        }

        if( uitvoer ) {
            ftd_string_free(uitvoer);
        }

        ftd_event_free(event);

        return retval;
    }

    /* Verwerk de uitvoer */
    eventInfo = ftd_eventinfo_parse(uitvoer);

    ftd_string_free( uitvoer );

    if (eventInfo == NULL) {
        g_warning("ftd_eventinfo_fetch(): Parsen van gegevens mislukt\n");
        return ERROR_PARSE;
    }

    // Zet de gegevens over van eventInfo naar eventOrig
    if (event->announcement) {
        ftd_string_free(event->announcement);
    }

    event->announcement = ftd_string_new(ftd_string_value(eventInfo->announcement));

    if (event->description) {
        ftd_string_free(event->description);
    }

    event->description = ftd_string_new(ftd_string_value(eventInfo->description));

    if (event->sig) {
        ftd_string_free(event->sig);
    }

    event->sig = ftd_string_new(ftd_string_value(eventInfo->sig));

    event->fileType = eventInfo->fileType;
    event->aantalFiles = eventInfo->aantalFiles;
    event->fileStart = eventInfo->fileStart;

    if (event->image) {
        ftd_string_free(event->image);
    }

    event->image = ftd_string_new(ftd_string_value(eventInfo->image));

    event->mp3Tracks = eventInfo->mp3Tracks;
    eventInfo->mp3Tracks = NULL;

    ftd_event_free(eventInfo);

    // Voeg het event toe aan de eventlist
    ftd_eventlist_add_or_replace_event(core->eventlist, event);

    // Bewaar de gegevens in de posts.db
    ftd_eventlist_save(core->eventlist);

    ftd_event_free(event);

    return ERROR_NONE;
}

/**
 * Zoekt op de FTD servers de gegevens van het gegeven event op.
 *
 * @arg     eventid     Het FTD-nummer van het gezochte event.
 *
 * @return  Een nieuw event met de gezochte gegevens of NULL indien deze niet gevonden werden.
 */
FtdEvent *
ftd_eventinfo_findpost(int eventid)
{
    FtdList     *params = NULL;
    FtdEvent    *event;
    char         postnummer[10];
    FtdString   *uitvoer;
    int          retval;

    snprintf(postnummer, sizeof(postnummer), "%i", eventid);
    params = ftd_list_append(params, ftd_http_parameter_new("id", postnummer));

    retval = ftd_http_curl_execute(FTD_URL_FIND_POST, params, TRUE, &uitvoer, TRUE, NULL, TRUE);
    ftd_http_parameter_free_all(params);
    if (retval) {
        return NULL;
    }

    /* Verwerk de uitvoer */
    event = ftd_eventinfo_parse_findpost(uitvoer);

    if (!event) {
        g_print("uitvoer = %s\n", ftd_string_value(uitvoer));
    }

    ftd_string_free(uitvoer);

    return event;
}
