
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

#include "../modsite/site.h"

#include "m3_server_factory.h"
#include "m3_server.h"

struct s_M3ServerFactory
{
    lstTlist *serverlist;
};

static void m3_server_factory_parse (M3ServerFactory *instance, const char *siteid);

M3ServerFactory *
m3_server_factory_new (const char *siteid)
{
    M3ServerFactory *instance = (M3ServerFactory *) malloc (sizeof (M3ServerFactory));

    instance->serverlist = lstFlist_create (m3_server_destroy);

    m3_server_factory_parse (instance, siteid);

    return (instance);
}

void
m3_server_factory_destroy (void *ptr)
{
    M3ServerFactory *instance = (M3ServerFactory *) ptr;

    lstFlist_free (instance->serverlist);

    free (instance);
}

M3Server *
m3_server_factory_find_mountpoint (M3ServerFactory *instance, const char *mountpoint)
{
    lstTlist_elem *ep;

    for (ep = lstFlist_head (instance->serverlist); ep; ep = lstFlist_next (ep))
    {
        M3Server *server = (M3Server *) lstFlist_data (ep);

        if (strcmp (m3_server_mountpoint_get (server), mountpoint) == 0)
        {
            return (server);
        }
    }

    return (NULL);
}

static void
m3_server_factory_add (M3ServerFactory *instance, M3Server *server)
{
    lstFlist_add_next (instance->serverlist, lstFlist_tail (instance->serverlist), server);
}

static void
m3_server_factory_parse (M3ServerFactory *instance, const char *siteid)
{
    const xmlTtag *config = siteFconfig_get_by_siteid (siteid);
    xmlTiterator *iter;
    const xmlTtag *tag;

    if (config == NULL)
    {
        return;
    }

    iter = xmlFiterator_init (config);

    if (iter == NULL)
    {
        return;
    }

    while ((tag = xmlFiterator_next_name (iter, "m3")) != NULL)
    {
        M3Server *server = m3_server_new();

        if (m3_server_parse (server, siteid, tag) == true)
        {
            if (m3_server_factory_find_mountpoint (instance, m3_server_mountpoint_get (server)) == NULL)
            {
                m3_server_factory_add (instance, server);
            }
            else
            {
                logFmsg (CONT_LOG_ERROR, "mod/m3: Found a duplicate mountpoint for site %s: %s", 
                        siteid, m3_server_mountpoint_get (server));

                m3_server_destroy (server);
            }
        }
        else
        {
            logFmsg (CONT_LOG_ERROR, "mod/m3: Could not parse m3 entry for site %s", 
                    siteid);

            m3_server_destroy (server);
        }
    }
    
    xmlFiterator_free (iter);
}
