#include "http_control.h"
#include "esp_log.h"
#include <string.h>
#include "../html/volume.html.h"

/* Our URI handler function to be called during GET /uri request */
esp_err_t get_handler(httpd_req_t *req)
{
    /* Send a simple response */
    const char resp[] = "URI GET Response";
    httpd_resp_send(req, resp, HTTPD_RESP_USE_STRLEN);
    return ESP_OK;
}

esp_err_t index_handler(httpd_req_t *req)
{
    /* Send a simple response */
    httpd_resp_send(req,  volume_HTML_String, HTTPD_RESP_USE_STRLEN);
    return ESP_OK;
}

esp_err_t volumeChangeCB(httpd_req_t *req)
{
    char buffer[100];
    if (httpd_req_get_url_query_str(req, buffer, 100) == ESP_OK)
    {
        char param[20];
        httpd_query_key_value(buffer, "channel", param, 10);
        int channelNo = atoi(param);
        httpd_query_key_value(req->uri, "value", param, 10);
        int volume = atoi(param);

        ESP_LOGI("HTTP", "Channel %d: %d", channelNo, volume);
    }
    else
    {
        char buffer[100];
        snprintf(buffer,100,"{\"channel1\":%d,\"channel2\":%d}",0,0);
        httpd_resp_send(req, buffer, HTTPD_RESP_USE_STRLEN);
        return ESP_OK;
    }

    /* Send a simple response */
    const char resp[] = "200 OK";
    httpd_resp_send(req, resp, HTTPD_RESP_USE_STRLEN);
    return ESP_OK;
}

esp_err_t getVolumeLevel(httpd_req_t *req)
{
    int uriLen =strlen(req->uri);
    char channelNo =req->uri[uriLen-1];
    switch(channelNo)
    {
        case '1':
        httpd_resp_send(req, "0", HTTPD_RESP_USE_STRLEN);
        break;
        case '2':
        httpd_resp_send(req, "0", HTTPD_RESP_USE_STRLEN);
        break;
        default:
        httpd_resp_send(req, "ERROR", HTTPD_RESP_USE_STRLEN);
        break;
    }
    return ESP_OK;
}

/* Our URI handler function to be called during POST /uri request */
esp_err_t post_handler(httpd_req_t *req)
{
    /* Destination buffer for content of HTTP POST request.
     * httpd_req_recv() accepts char* only, but content could
     * as well be any binary data (needs type casting).
     * In case of string data, null termination will be absent, and
     * content length would give length of string */
    char content[100];

    /* Truncate if content length larger than the buffer */
    size_t recv_size = MIN(req->content_len, sizeof(content));

    int ret = httpd_req_recv(req, content, recv_size);
    if (ret <= 0)
    { /* 0 return value indicates connection closed */
        /* Check if timeout occurred */
        if (ret == HTTPD_SOCK_ERR_TIMEOUT)
        {
            /* In case of timeout one can choose to retry calling
             * httpd_req_recv(), but to keep it simple, here we
             * respond with an HTTP 408 (Request Timeout) error */
            httpd_resp_send_408(req);
        }
        /* In case of error, returning ESP_FAIL will
         * ensure that the underlying socket is closed */
        return ESP_FAIL;
    }

    /* Send a simple response */
    const char resp[] = "URI POST Response";
    httpd_resp_send(req, resp, HTTPD_RESP_USE_STRLEN);
    return ESP_OK;
}

/* URI handler structure for GET /uri */
httpd_uri_t uri_get = {
    .uri = "/uri",
    .method = HTTP_GET,
    .handler = get_handler,
    .user_ctx = NULL};

/* URI handler structure for POST /uri */
httpd_uri_t uri_post = {
    .uri = "/uri",
    .method = HTTP_POST,
    .handler = post_handler,
    .user_ctx = NULL};

httpd_uri_t index_get = {
    .uri = "/",
    .method = HTTP_GET,
    .handler = index_handler,
    .user_ctx = NULL};

httpd_uri_t volumeChangeGet = {
    .uri = "/volume",
    .method = HTTP_GET,
    .handler = volumeChangeCB,
    .user_ctx = NULL};

httpd_uri_t channel1_volume_get = {
    .uri = "/volume/channel*",
    .method = HTTP_GET,
    .handler = getVolumeLevel,
    .user_ctx = NULL};

/* Function for starting the webserver */
httpd_handle_t start_webserver(void)
{
    /* Generate default configuration */
    httpd_config_t config = HTTPD_DEFAULT_CONFIG();

    /* Empty handle to esp_http_server */
    httpd_handle_t server = NULL;

    config.uri_match_fn = httpd_uri_match_wildcard;
    config.max_uri_handlers = 16;

    /* Start the httpd server */
    if (httpd_start(&server, &config) == ESP_OK)
    {
        /* Register URI handlers */
        httpd_register_uri_handler(server, &index_get);
        httpd_register_uri_handler(server, &volumeChangeGet);
        httpd_register_uri_handler(server, &channel1_volume_get);
    }
    /* If server failed to start, handle will be NULL */
    return server;
}

/* Function for stopping the webserver */
void stop_webserver(httpd_handle_t server)
{
    if (server)
    {
        /* Stop the httpd server */
        httpd_stop(server);
    }
}