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

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

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;
}


/* -------------------------
   headers for live stream
------------------------- */

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");

    http_SetHeader(ctx->http_resp,
        "ICY-MetaInt: 16000");
}


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

VCL_VOID
vmod_add_listener(VRT_CTX)
{
    listeners++;
}

VCL_INT
vmod_get_listeners(VRT_CTX)
{
    return listeners;
}


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

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

    return rand() % max;
}


/* -------------------------
   geo routing (simple)
------------------------- */

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

    /* simple example */

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

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

    return 2;
}


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

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

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