
#include <stdlib.h>
#include <pthread.h>

#include "http_request_list.h"

#include "http.h"

struct s_HttpRequestList
{
    hshTvoid_list   *list;

    pthread_rwlock_t list_lock;
};

HttpRequestList *
http_request_list_new()
{
    HttpRequestList *request_list = malloc (sizeof (HttpRequestList));

    request_list->list = hshFvoid_init (http_request_destroy);

    pthread_rwlock_init (&request_list->list_lock, NULL);

    return (request_list);
}

void
http_request_list_destroy (void *ptr)
{
    HttpRequestList *request_list = (HttpRequestList *) ptr;

    pthread_rwlock_destroy (&request_list->list_lock);

    hshFvoid_destroy (request_list->list);

    free (request_list);
}

void
http_request_list_addRequest (HttpRequestList *request_list, HttpRequest *resp)
{
    pthread_rwlock_wrlock (&request_list->list_lock);

    hshFvoid_add (request_list->list, http_request_getToken (resp), resp);

#ifdef TRACE_REQUEST_LIST
    printf (" -- added request %s\n", http_request_getToken (resp));
#endif

    pthread_rwlock_unlock (&request_list->list_lock);
}

void
http_request_list_removeRequest (HttpRequestList *request_list, const char *token)
{
    pthread_rwlock_wrlock (&request_list->list_lock);

#ifdef TRACE_REQUEST_LIST
    printf (" -- removed request %s\n", token);
#endif

    hshFvoid_del (request_list->list, token);

    pthread_rwlock_unlock (&request_list->list_lock);
}

HttpRequest *
http_request_list_getRequest (HttpRequestList *request_list, const char *token)
{
    HttpRequest *request;

    pthread_rwlock_rdlock (&request_list->list_lock);

    request = (HttpRequest *) hshFvoid_find (request_list->list, token);

    pthread_rwlock_unlock (&request_list->list_lock);

    return (request);
}

dynTstring *
http_request_list_getDiag (HttpRequestList *request_list)
{
    dynTstring *string;

    pthread_rwlock_rdlock (&request_list->list_lock);

    string = hshFdiag_output (request_list->list);

    pthread_rwlock_unlock (&request_list->list_lock);

    return (string);
}
