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

#include "fd_watcher_entry.h"
#include "threadpool.h"

struct s_FDWatcherEntry
{
    int fd;

    short   events;
    short   revents;

    FDWatcherDelegate function;

    void *context;
};

FDWatcherEntry *
fd_watcher_entry_new (int fd, FDWatcherDelegate function, void *context, short events)
{
    FDWatcherEntry *instance = (FDWatcherEntry *) malloc (sizeof (FDWatcherEntry));

    instance->fd = fd;
    instance->function = function;
    instance->context = context;
    instance->events = events;

    return (instance);
}

void
fd_watcher_entry_destroy (void *ptr)
{
    FDWatcherEntry *instance = (FDWatcherEntry *) ptr;

    free (instance);
}

int
fd_watcher_entry_getFD (FDWatcherEntry *instance)
{
    return (instance->fd);
}

short
fd_watcher_entry_getEvents (FDWatcherEntry *instance)
{
    return (instance->events);
}

void
fd_watcher_entry_addEvent (FDWatcherEntry *instance, short event)
{
    instance->events |= event;
}

static void
fd_watcher_entry_internalInvoke (void *context)
{
    FDWatcherEntry *instance = context;

    instance->function (instance->context, instance->fd, instance->revents);

    fd_watcher_entry_destroy (instance);
}

void
fd_watcher_entry_invoke (FDWatcherEntry *instance, short events)
{
    instance->revents = events;

    threadpool_queueUserWorkItem (threadpool_getInstance(), 
            fd_watcher_entry_internalInvoke, instance);
}

