/* ====================================================================
 * 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 <glib/gprintf.h>
#include <libxml/parser.h>
#include <libxml/tree.h>

int
ftd_con_event_print(int eventId, gboolean offline)
{
    FtdEvent *event;
    FtdCategory *cat;
    FtdList *list;
    int retval;
    char * errmsg;
    gboolean first;
    FtdString *newsgroups;
    FTDEventlist *eventlist;

    if (eventId == 0) {
        g_warning("ftd_con_event_print(): Ongeldige eventId!\n");
        return 1;
    }

    eventlist = ftd_eventlist_get();
    event = ftd_eventlist_lookup_id(eventlist, eventId);
    g_object_unref(eventlist);

    if (!event) {
        g_warning("ftd_con_event_print(): Kan FTD event behorende bij eventId '%i' niet vinden!\n", eventId);
        return 2;
    }

    cat = ftd_category_get_parent(event->cat);
    if (!cat) {
        g_warning("ftd_con_event_print(): Event %i lijkt in geen enkele categorie (%i) te vallen!\n", event->postId, event->cat);
        ftd_event_free(event);
        return 3;
    }

    if (!offline) {
        retval = ftd_eventinfo_fetch(eventId, &errmsg);
        if(retval != ERROR_NONE) {
            gchar *msg = ftd_error_msg(retval, errmsg);
            g_warning("%s", msg);
            if (errmsg) {
                g_free(errmsg);
            }
            g_free(msg);
            ftd_event_free(event);
            return 4;
        }
    }

    list = event->groups;
    newsgroups = ftd_string_new("");
    while (list) {
        FtdString *groupId = ftd_list_value(list);
        FtdGroup *group;

        group = ftd_group_by_id(atoi(ftd_string_value(groupId)));

        if (!group) {
            g_warning("Nieuwsgroep id %s behorende bij FTD ID %i onbekend!\n", ftd_string_value(groupId), event->postId);
            list = ftd_list_next(list);
            continue;
        }

        if (ftd_string_length(newsgroups) > 0) {
            newsgroups = ftd_string_append(newsgroups, ", ");
        }

        newsgroups = ftd_string_append(newsgroups, ftd_string_value(group->groupName));

        list = ftd_list_next(list);
    }

    g_printf("eventId :\t%i\n", event->postId);
    g_printf("created :\t%s\n", ftd_string_date(event->stamp));
    g_printf("updated :\t%s\n", ftd_string_date(event->updated));
    g_printf("status :\t%s\n", ftd_string_status(event->status));
    g_printf("posttitle :\t%s\n", ftd_string_value(event->title));
    g_printf("poster :\t%s\n", ftd_string_value(event->poster));
    g_printf("website :\t%s\n", ftd_string_value(event->link));
    g_printf("nieuwsgroepen :\t%s\n", ftd_string_value(newsgroups));
    g_printf("categorie :\t%s\n", ftd_string_value(cat->name));
    list = event->tags;
    while( list ) {
        FtdString *tagcode = ftd_list_value( list );
        const FtdTag *tag = ftd_tag_find( tagcode, event->cat );
        if( !tag ) {
            g_warning( "Unknown tag: %s", ftd_string_value( tagcode ) );
            list = ftd_list_next( list );
            continue;
        }
        g_printf( "%s :\t%s\n", ftd_string_value( tag->parent->name ), ftd_string_value( tag->name ) );
        list = ftd_list_next( list );
    }
    if( event->announcement ) {
        if( ftd_string_length( event->announcement ) ) {
            g_printf("announcement :\n\t%s\n", ftd_string_value( ftd_string_replace( event->announcement, "<br />", "\n\t" ) ) );
        }
    }
    if( event->description ) {
        if( ftd_string_length( event->description ) > 0 ) {
            g_printf("description :\n\t%s\n", ftd_string_value( ftd_string_replace( event->description, "<br />", "\n\t" ) ) );
        }
    }
    if( event->sig ) {
        if( ftd_string_length( event->sig ) > 0 ) {
            g_printf("sig :\n\t%s\n", ftd_string_value( ftd_string_replace( event->sig, "<br />", "\n\t" ) ) );
        }
    }
    if( event->image ) {
        if( ftd_string_length( event->image ) > 0 && strcmp( ftd_string_value( event->image ), "http://" ) ) {
            g_printf( "image-url :\t%s\n", ftd_string_value( event->image ) );
        }
    }

    ftd_string_free(newsgroups);

    // TODO: Filename + PAR files

    ftd_event_free(event);

    return 0;
}

int
ftd_con_event_print_xml(int eventId, gboolean offline)
{
    xmlDocPtr doc = NULL;
    xmlNodePtr rootNode, tmpNode, cdataNode, eventNode = NULL;
    FtdString *str;
    FtdEvent *event;
    FtdCategory *cat;
    FtdList *list;
    char *errmsg;
    int retval;
    FTDEventlist *eventlist;

    if (eventId == 0) {
        g_warning("ftd_con_event_print_xml(): Ongeldige eventId!\n");
        return 1;
    }

    if (!offline) {
        retval = ftd_eventinfo_fetch( eventId, &errmsg );
        if(retval != ERROR_NONE) {
            gchar *msg = ftd_error_msg(retval, errmsg);
            g_warning("%s", msg);
            if (errmsg) {
                g_free(errmsg);
            }
            g_free(msg);
            return 4;
        }
    }

    doc = xmlNewDoc(BAD_CAST "1.0");
    rootNode = xmlNewNode(NULL, BAD_CAST "FTD");
    xmlDocSetRootElement(doc, rootNode);

    eventlist = ftd_eventlist_get();
    event = ftd_eventlist_lookup_id(eventlist, eventId);
    g_object_unref(eventlist);

    if (!event) {
        xmlSaveFormatFileEnc("-", doc, "UTF-8", 1);
        xmlFreeDoc(doc);
        //xmlCleanupParser();
        return 2;
    }

    cat = ftd_category_get_parent(event->cat);
    if (!cat) {
        g_warning("ftd_con_event_print(): Event %i lijkt in geen enkele categorie (%i) te vallen!\n", event->postId, event->cat);
        ftd_event_free(event);
        return 3;
    }

    eventNode = xmlNewNode(NULL, BAD_CAST "Posting");
    xmlAddChild(rootNode, eventNode);

    str = ftd_string_integer(event->postId);
    xmlNewTextChild(eventNode, NULL, "ID", ftd_string_value(str));
    ftd_string_free(str);

    str = ftd_string_integer(event->stamp);
    xmlNewTextChild(eventNode, NULL, "Created", ftd_string_value(str));
    ftd_string_free(str);

    str = ftd_string_integer(event->updated);
    xmlNewTextChild(eventNode, NULL, "Updated", ftd_string_value(str));
    ftd_string_free(str);

    xmlNewTextChild(eventNode, NULL, "Status", ftd_string_status(event->status));
    if( event->title ) {
        tmpNode = xmlNewNode( NULL, "Title" );
        cdataNode = xmlNewCDataBlock( doc, ftd_string_value( event->title ), ftd_string_length( event->title ) );
        xmlAddChild( tmpNode, cdataNode );
        xmlAddChild( eventNode, tmpNode );
    }
    tmpNode = xmlNewNode( NULL, "Poster" );
    cdataNode = xmlNewCDataBlock( doc, ftd_string_value( event->poster ), ftd_string_length( event->poster ) );
    xmlAddChild( tmpNode, cdataNode );
    xmlAddChild( eventNode, tmpNode );
    if (event->link) {
        if (ftd_string_length(event->link) > 0) {
            tmpNode = xmlNewNode( NULL, "Website" );
            cdataNode = xmlNewCDataBlock( doc, ftd_string_value( event->link ), ftd_string_length( event->link ) );
            xmlAddChild( tmpNode, cdataNode );
            xmlAddChild( eventNode, tmpNode );
        }
    }

    list = event->groups;
    while (list) {
        FtdString *groupId = ftd_list_value(list);
        FtdGroup *group;

        group = ftd_group_by_id(atoi(ftd_string_value(groupId)));
        if (!group) {
            g_warning("Nieuwsgroep id %s behorende bij FTD ID %i onbekend!\n", ftd_string_value(groupId), event->postId);
            list = ftd_list_next(list);
            continue;
        }

        tmpNode = xmlNewNode(NULL, "Newsgroup");
        cdataNode = xmlNewCDataBlock(doc, ftd_string_value(group->groupName), ftd_string_length(group->groupName));
        xmlAddChild(tmpNode, cdataNode);
        xmlAddChild(eventNode, tmpNode);

        list = ftd_list_next(list);
    }

    tmpNode = xmlNewNode( NULL, "Cat" );
    cdataNode = xmlNewCDataBlock( doc, ftd_string_value( cat->name ), ftd_string_length( cat->name ) );
    xmlAddChild( tmpNode, cdataNode );
    xmlAddChild( eventNode, tmpNode );

    list = event->tags;
    while( list ) {
        FtdString *tagcode = ftd_list_value( list );
        const FtdTag *tag = ftd_tag_find( tagcode, event->cat );
        if( !tag ) {
            g_warning( "Unknown tag: %s", ftd_string_value( tagcode ) );
            list = ftd_list_next( list );
            continue;
        }
        tmpNode = xmlNewNode( NULL, ftd_string_value(tag->parent->name));
        cdataNode = xmlNewCDataBlock( doc, ftd_string_value( tag->name ), ftd_string_length( tag->name ) );
        xmlAddChild( tmpNode, cdataNode );
        xmlAddChild( eventNode, tmpNode );
        list = ftd_list_next( list );
    }

    if( event->announcement ) {
        if( ftd_string_length( event->announcement ) > 0 ) {
            tmpNode = xmlNewNode( NULL, "Announcement" );
            cdataNode = xmlNewCDataBlock( doc, ftd_string_value( event->announcement ), ftd_string_length( event->announcement ) );
            xmlAddChild( tmpNode, cdataNode );
            xmlAddChild( eventNode, tmpNode );
        }
    }
    if( event->description ) {
        if( ftd_string_length( event->description ) > 0 ) {
            tmpNode = xmlNewNode( NULL, "Description" );
            cdataNode = xmlNewCDataBlock( doc, ftd_string_value( event->description ), ftd_string_length( event->description ) );
            xmlAddChild( tmpNode, cdataNode );
            xmlAddChild( eventNode, tmpNode );
        }
    }
    if( event->sig ) {
        if( ftd_string_length( event->sig ) > 0 ) {
            tmpNode = xmlNewNode( NULL, "Sig" );
            cdataNode = xmlNewCDataBlock( doc, ftd_string_value( event->sig ), ftd_string_length( event->sig ) );
            xmlAddChild( tmpNode, cdataNode );
            xmlAddChild( eventNode, tmpNode );
        }
    }
    if( event->image ) {
        if( ftd_string_length( event->image ) > 0 && strcmp( ftd_string_value( event->image ), "http://" ) ) {
            tmpNode = xmlNewNode( NULL, "Image" );
            cdataNode = xmlNewCDataBlock( doc, ftd_string_value( event->image ), ftd_string_length( event->image ) );
            xmlAddChild( tmpNode, cdataNode );
            xmlAddChild( eventNode, tmpNode );
        }
    }

    // TODO: Filename + PAR files

    xmlSaveFormatFileEnc("-", doc, "UTF-8", 1);
    xmlFreeDoc(doc);
    //xmlCleanupParser();

    ftd_event_free(event);

    return 0;
}
