#include "tuple.h"
#include "dablooms.h"
#include "session_filter.h"

struct session_filter
{
    struct expiry_dablooms_handle *dablooms;
};

struct session_filter *session_filter_new(uint32_t capacity, uint32_t timeout, double error_rate, uint64_t now)
{
    struct session_filter *filter = (struct session_filter *)calloc(1, sizeof(struct session_filter));
    if (filter == NULL)
    {
        return NULL;
    }

    filter->dablooms = expiry_dablooms_new(capacity, error_rate, now, timeout);
    if (filter->dablooms == NULL)
    {
        free(filter);
        return NULL;
    }

    return filter;
}

void session_filter_free(struct session_filter *filter)
{
    if (filter)
    {
        if (filter->dablooms)
        {
            expiry_dablooms_free(filter->dablooms);
            filter->dablooms = NULL;
        }
        free(filter);
        filter = NULL;
    }
}

// return 1: found
// reutrn 0: no found
int session_filter_lookup(struct session_filter *filter, const struct tuple6 *key, uint64_t now)
{
    if (expiry_dablooms_search(filter->dablooms, (const char *)key, sizeof(struct tuple6), now) == 1)
    {
        return 1;
    }

    return 0;
}

void session_filter_add(struct session_filter *filter, const struct tuple6 *key, uint64_t now)
{
    struct tuple6 reverse_key;
    tuple6_reverse(key, &reverse_key);

    expiry_dablooms_add(filter->dablooms, (const char *)key, sizeof(struct tuple6), now);
    expiry_dablooms_add(filter->dablooms, (const char *)&reverse_key, sizeof(struct tuple6), now);
}
