#include "vrt.h"
#include "cache/cache.h"
#include "vcc_radio_if.h"

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

static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

static int listeners = 0;


/* -------------------
   stream detect
------------------- */

VCL_BOOL
vmod_is_stream(VRT_CTX, VCL_STRING url)
{
    if (!url)
        return 0;

    if (strstr(url,".mp3") ||
        strstr(url,".aac") ||
        strstr(url,".ogg") ||
        strstr(url,".m3u8") ||
        strstr(url,"/stream"))
        return 1;

    return 0;
}


/* -------------------
   listener counter
------------------- */

VCL_VOID
vmod_add_listener(VRT_CTX)
{
    pthread_mutex_lock(&lock);
    listeners++;
    pthread_mutex_unlock(&lock);
}

VCL_INT
vmod_get_listeners(VRT_CTX)
{
    return listeners;
}


/* -------------------
   burst protection
------------------- */

VCL_BOOL
vmod_allow_listener(VRT_CTX, VCL_INT limit)
{
    if (listeners >= limit)
        return 0;

    return 1;
}


/* -------------------
   backend picker
------------------- */

VCL_INT
vmod_pick_backend(VRT_CTX, VCL_INT max)
{
    if (max <= 0)
        return 0;

    return rand() % max;
}


/* -------------------
   sticky backend
------------------- */

VCL_INT
vmod_sticky_backend(VRT_CTX,
    VCL_STRING ip,
    VCL_INT max)
{
    if (!ip || max <= 0)
        return 0;

    int hash = 0;

    for (int i=0; ip[i]; i++)
        hash += ip[i];

    return hash % max;
}


/* -------------------
   geo route (stub)
------------------- */

VCL_INT
vmod_geo_route(VRT_CTX, VCL_STRING ip)
{
    if (!ip)
        return 0;

    if (strncmp(ip,"10.",3)==0)
        return 0;

    if (strncmp(ip,"172.",4)==0)
        return 1;

    return 2;
}


/* -------------------
   headers
------------------- */

VCL_VOID
vmod_stream_headers(VRT_CTX)
{
    if (!ctx->http_resp)
        return;

    http_Unset(ctx->http_resp, H_Content_Length);

    http_SetHeader(ctx->http_resp,
        "Cache-Control: no-cache");

    http_SetHeader(ctx->http_resp,
        "Connection: keep-alive");
}


/* -------------------
   icy metadata
------------------- */

VCL_VOID
vmod_icy_headers(VRT_CTX)
{
    if (!ctx->http_resp)
        return;

    http_SetHeader(ctx->http_resp,
        "icy-metaint:16000");
}


/* -------------------
   HLS cache
------------------- */

VCL_VOID
vmod_hls_cache(VRT_CTX)
{
    if (!ctx->http_resp)
        return;

    http_SetHeader(ctx->http_resp,
        "Cache-Control: public,max-age=5");
}


/* -------------------
   stats
------------------- */

VCL_STRING
vmod_stats(VRT_CTX)
{
    static char buf[128];

    snprintf(buf, sizeof(buf),
        "listeners=%d",
        listeners);

    return buf;
}
