#include <logger.h>
#include <cJSON.h>
#include <mongoose.h>
#include <macros.h>
#include <endpoint.h>

void
endpoint_func_index(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response)
{
    (void)args;
    (void)hm;
    (void)nc;
    (void)response;

    response->status_code = 0;

    mg_serve_http(nc, hm, global_config.http_server_opts);
}

void
endpoint_func_not_found(struct mg_connection *nc, struct http_message *hm, endpoint_args_t *args, endpoint_response_t *response)
{
    (void)args;
    (void)hm;
    (void)nc;
    
    if(access(global_config.not_found_file, R_OK) != -1)
    {
        struct mg_str mime_type = mg_mk_str(global_config.not_found_file_type);
        response->status_code = 0;
        mg_http_serve_file(nc, hm, global_config.not_found_file, mime_type, mg_mk_str(""));
    }
    else
    {
        LOGGER_DEBUG("404 file not found\n");
        response->status_code = 404;
        response->content_type = global_config.not_found_content_type;
        response->content_length = strlen(global_config.not_found_content);
        response->content = global_config.not_found_content;
        response->alloced_content = false;
    }

}

void
endpoint_response_text(endpoint_response_t *response, int status_code, const char *content, int content_length)
{
    if(content == NULL)
    {
        content = "";
        content_length = 0;
    }

    response->status_code = status_code;
    response->content_type = "text/plain";
    if(content_length >= 0)
    {
        response->content_length = content_length;
        response->alloced_content = false;
    }
    else
    {
        response->content_length = strlen(content);
        response->alloced_content = true;
    }
    response->content = content;
}

void
endpoint_response_json(endpoint_response_t *response, int status_code, const cJSON *json_root)
{
    if(json_root != NULL)
    {
        char *json_str = cJSON_Print(json_root);
        if (json_str != NULL)
        {
            response->status_code = status_code;
            response->content_type = "application/json";
            response->content_length = strlen(json_str);
            response->content = json_str;
            response->alloced_content = true;

            return;
        }
    }

    LOGGER_ERR("failed to print schedule json\n");

    static const char content[] = "failed to print json";
    endpoint_response_text(response, status_code, content, STRLEN(content));
}