/* ====================================================================
 * 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>

struct list_print_data {
    time_t nu;
    time_t age;
    gboolean headerPrinted;
};

static gboolean
list_print_func(gpointer key, gpointer value, gpointer data)
{
    struct list_print_data *func_data = (struct list_print_data *) data;
    FtdEvent *event = (FtdEvent *) value;
    gboolean first;
    char *created;
    char *updated;
    FtdCategory *cat;

    g_assert(event);

    if (func_data->age > 0 && event->stamp < func_data->nu - func_data->age) {
        return FALSE;
    }

    if (func_data->age == -1 && event->stamp < ftd_config_get()->prevCheck) {
        return FALSE;
    }

    created = ftd_string_date(event->stamp);
    updated = ftd_string_date(event->updated);

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

    if (!func_data->headerPrinted) {
        func_data->headerPrinted = TRUE;
        g_print("FTD ID\tCat\tStatus\tDate created\tLast updated\tName of poster\tTitle\n");
    }

    g_print("%i\t%s\t%s\t%s\t%s\t%s\t%s\n", event->postId, ftd_string_value(cat->name), ftd_string_status(event->status), created, updated, ftd_string_value(event->poster), ftd_string_value(event->title));

    g_free(created);
    g_free(updated);

    return FALSE;
}

int
ftd_con_list_print(time_t age, const char *zoekterm)
{
    struct list_print_data func_data;
    FTDEventlist *eventlist;

    eventlist = ftd_eventlist_get();

    if (zoekterm) {
        FtdFilter *filterNieuw;

        filterNieuw = ftd_filter_new_filter();
        filterNieuw->title = ftd_string_new(zoekterm);
        ftd_eventlist_apply_filter(eventlist, filterNieuw);
        ftd_filter_free_filter(filterNieuw);
    }

    if (ftd_eventlist_get_count(eventlist, FALSE) == 0) {
        g_warning("ftd_eventlist_get_count() == 0\n"
                  "Heb je de lijst met FTD postings reeds geupdated ?");
        return 1;
    }

    func_data.nu = time(NULL);
    func_data.age = age;
    func_data.headerPrinted = FALSE;

    ftd_eventlist_foreach(eventlist, (zoekterm != NULL), TRUE, list_print_func, &func_data);

    g_object_unref(eventlist);

    return 0;
}

struct list_print_xml_data {
    xmlDocPtr doc;
    xmlNodePtr rootNode;
    time_t nu;
    time_t age;
};

static gboolean
list_print_xml_func(gpointer key, gpointer value, gpointer data)
{
    xmlNodePtr eventNode;
    FtdString *str;
    FtdCategory *cat;
    FtdList *tags;
    struct list_print_xml_data *func_data = (struct list_print_xml_data *) data;
    FtdEvent *event = (FtdEvent *) value;
    xmlNodePtr tmpNode, cdataNode = NULL;
    FtdList *list;

    if (func_data->age > 0 && event->stamp < func_data->nu - func_data->age) {
        return FALSE;
    }

    if (func_data->age == -1 && event->stamp < ftd_config_get()->prevCheck) {
        return FALSE;
    }

    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);
        return FALSE;
    }

    eventNode = xmlNewNode(NULL, BAD_CAST "Posting");
    xmlAddChild(func_data->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));

    tmpNode = xmlNewNode(NULL, "Title");
    cdataNode = xmlNewCDataBlock(func_data->doc, ftd_string_value(event->title), ftd_string_length(event->title));
    xmlAddChild(tmpNode, cdataNode);
    xmlAddChild(eventNode, tmpNode);

    tmpNode = xmlNewNode(NULL, "Poster");
    cdataNode = xmlNewCDataBlock(func_data->doc, ftd_string_value(event->poster), ftd_string_length(event->poster));
    xmlAddChild(tmpNode, cdataNode);
    xmlAddChild(eventNode, tmpNode);

    list = event->groups;
    while (list) {
        FtdString *groupId = ftd_list_value(list);
        FtdGroup *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, "Group");
        cdataNode = xmlNewCDataBlock(func_data->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(func_data->doc, ftd_string_value(cat->name), ftd_string_length(cat->name));
    xmlAddChild( tmpNode, cdataNode );
    xmlAddChild( eventNode, tmpNode );

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

    if (event->link) {
        if (ftd_string_length(event->link) > 0) {
            tmpNode = xmlNewNode(NULL, "Website");
            cdataNode = xmlNewCDataBlock(func_data->doc, ftd_string_value(event->link), ftd_string_length(event->link));
            xmlAddChild(tmpNode, cdataNode);
            xmlAddChild(eventNode, tmpNode);
        }
    }

    return FALSE;
}

int
ftd_con_list_print_xml(time_t age, const char *zoekterm)
{
    xmlDocPtr doc = NULL;
    xmlNodePtr rootNode;
    struct list_print_xml_data func_data;
    FTDEventlist *eventlist;

    eventlist = ftd_eventlist_get();

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

    if (zoekterm) {
        FtdFilter *filterNieuw;

        filterNieuw = ftd_filter_new_filter();
        filterNieuw->title = ftd_string_new(zoekterm);
        ftd_eventlist_apply_filter(eventlist, filterNieuw);
        ftd_filter_free_filter(filterNieuw);
    }

    if (ftd_eventlist_get_count(eventlist, FALSE) == 0) {
        g_warning("ftd_eventlist_get_count() == 0\n"
                  "Heb je de lijst met FTD postings reeds geupdated ?");
        return 1;
    }

    func_data.age = age;
    func_data.doc = doc;
    func_data.nu = time(NULL);
    func_data.rootNode = rootNode;

    ftd_eventlist_foreach(eventlist, (zoekterm != NULL), TRUE, list_print_xml_func, &func_data);

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

    g_object_unref(eventlist);

    return 0;
}
