#include <cJSON.h>
#include <macros.h>
#include <constants.h>
#include <endpoints/api_v1_macros.h>
#include <logger.h>
#include <command.h>
#include <models/macro_action.h>
#include <models/macro.h>
#include <models/relay.h>
#include <models/tag.h>

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

    uuid_t target_uid;
    if(uuid_parse(args[0].value.v_str, target_uid))
    {
        M_RESPONSE_400_NO_VALID_ID(response);
        return;
    }

    macro_t* macro = macro_get_by_uid(target_uid);

    if(!macro)
    {
        M_RESPONSE_404_NO_MACRO_FOUND_FOR_ID(response);
        return;
    }

    cJSON *json = macro_to_json(macro);

    endpoint_response_json(response, 200, json);
    cJSON_Delete(json);
    macro_free(macro);
}

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

    uuid_t target_uid;
    if(uuid_parse(args[0].value.v_str, target_uid))
    {
        M_RESPONSE_400_NO_VALID_ID(response);
        return;
    }

    macro_t* macro = macro_get_by_uid(target_uid);

    if(!macro)
    {
        M_RESPONSE_404_NO_MACRO_FOUND_FOR_ID(response);
        return;
    }

    cJSON *json = cJSON_ParseWithLength(hm->body.p, hm->body.len);

    if(json == NULL)
    {
        M_RESPONSE_400_NO_VALID_JSON(response);
        return;
    }

    database_transaction_lock lock;
    database_transaction_begin(&lock);

    cJSON *json_name = cJSON_GetObjectItemCaseSensitive(json, "name");
    if(cJSON_IsString(json_name) && (json_name->valuestring != NULL))
    {
        strncpy(macro->name, json_name->valuestring, MAX_NAME_LENGTH);
        macro->name[MAX_NAME_LENGTH] = '\0';

        if(macro_save(macro))
        {
            database_transaction_rollback(&lock);
            cJSON_Delete(json);
            macro_free(macro);

            M_RESPONSE_500_FAILED_TO_SAVE_TO_DATABASE(response);
            return;
        }
    }

    macro_action_delete_for_macro(macro->id);

    cJSON *json_actions = cJSON_GetObjectItemCaseSensitive(json, "actions");
    if(cJSON_IsArray(json_actions))
    {
        cJSON *json_action;
        cJSON_ArrayForEach(json_action, json_actions)
        {
            cJSON *json_action_weekday = cJSON_GetObjectItemCaseSensitive(json_action, "weekday");
            if(!cJSON_IsNumber(json_action_weekday) || (json_action_weekday->valueint < 0) || (json_action_weekday->valueint > 6))
            {
                database_transaction_rollback(&lock);
                cJSON_Delete(json);
                macro_free(macro);

                M_RESPONSE_MSG(LOGGER_DEBUG, response, 400, "at least one action is missing a weekday");
                return;
            }

            cJSON *json_action_schedule = cJSON_GetObjectItemCaseSensitive(json_action, "schedule");
            if(!cJSON_IsObject(json_action_schedule))
            {
                database_transaction_rollback(&lock);
                cJSON_Delete(json);
                macro_free(macro);

                M_RESPONSE_MSG(LOGGER_DEBUG, response, 400, "at least one action is missing a schedule");
                return;
            }
            cJSON *json_action_schedule_uid = cJSON_GetObjectItemCaseSensitive(json_action_schedule, "id");
            if(!cJSON_IsString(json_action_schedule_uid) || (json_action_schedule_uid->valuestring == NULL))
            {
                database_transaction_rollback(&lock);
                cJSON_Delete(json);
                macro_free(macro);

                M_RESPONSE_MSG(LOGGER_DEBUG, response, 400, "at least one action is missing a schedule id");
                return;
            }
            uuid_t action_schedule_uid;
            if(schedule_uid_parse(json_action_schedule_uid->valuestring, action_schedule_uid))
            {
                database_transaction_rollback(&lock);
                cJSON_Delete(json);
                macro_free(macro);

                M_RESPONSE_MSG(LOGGER_DEBUG, response, 400, "at least one action has a bad schedule id");
                return;
            }

            schedule_t *action_schedule = schedule_get_by_uid(action_schedule_uid);
            if(action_schedule == NULL)
            {
                database_transaction_rollback(&lock);
                cJSON_Delete(json);
                macro_free(macro);

                M_RESPONSE_MSG(LOGGER_DEBUG, response, 400, "at least one action schedule was not found");
                return;
            }

            int action_schedule_id = action_schedule->id;
            schedule_free(action_schedule);


            cJSON *json_action_relay = cJSON_GetObjectItemCaseSensitive(json_action, "relay");
            if(!cJSON_IsObject(json_action_relay))
            {
                database_transaction_rollback(&lock);
                cJSON_Delete(json);
                macro_free(macro);

                M_RESPONSE_MSG(LOGGER_DEBUG, response, 400, "at least one action is missing a relay");
                return;
            }
            cJSON *json_action_relay_number = cJSON_GetObjectItemCaseSensitive(json_action_relay, "number");
            if(!cJSON_IsNumber(json_action_relay_number))
            {
                database_transaction_rollback(&lock);
                cJSON_Delete(json);
                macro_free(macro);

                M_RESPONSE_MSG(LOGGER_DEBUG, response, 400, "at least one action is missing a relay number");
                return;
            }
            cJSON *json_action_relay_controller_uid = cJSON_GetObjectItemCaseSensitive(json_action_relay, "controller_id");
            if(!cJSON_IsString(json_action_relay_controller_uid) || (json_action_relay_controller_uid->valuestring == NULL))
            {
                database_transaction_rollback(&lock);
                cJSON_Delete(json);
                macro_free(macro);

                M_RESPONSE_MSG(LOGGER_DEBUG, response, 400, "at least one action is missing a relay controller id");
                return;
            }
            uuid_t action_controller_uid;
            if(uuid_parse(json_action_relay_controller_uid->valuestring, action_controller_uid))
            {
                database_transaction_rollback(&lock);
                cJSON_Delete(json);
                macro_free(macro);

                M_RESPONSE_MSG(LOGGER_DEBUG, response, 400, "at least one action has a bad relay controller id");
                return;
            }

            controller_t *action_controller = controller_get_by_uid(action_controller_uid);
            if(action_controller == NULL)
            {
                database_transaction_rollback(&lock);
                cJSON_Delete(json);
                macro_free(macro);

                M_RESPONSE_MSG(LOGGER_DEBUG, response, 400, "at least one action relay controller was not found");
                return;
            }

            int controller_id = action_controller->id;
            int relay_num = json_action_relay_number->valueint;

            controller_free(action_controller);

            relay_t *action_relay = relay_get_for_controller(controller_id, relay_num);
            if(action_relay == NULL)
            {
                database_transaction_rollback(&lock);
                cJSON_Delete(json);
                macro_free(macro);

                M_RESPONSE_MSG(LOGGER_DEBUG, response, 400, "action relay was not found");
                return;
            }

            int action_relay_id = action_relay->id;
            relay_free(action_relay);


            macro_action_t *action = malloc(sizeof(macro_action_t));
            action->macro_id = macro->id;
            action->relay_id = action_relay_id;
            action->schedule_id = action_schedule_id;
            action->weekday = json_action_weekday->valueint;

            macro_action_insert(action);
            free(action);
        }
    }

    database_transaction_commit(&lock);

    cJSON_Delete(json);
    json = macro_to_json(macro);

    endpoint_response_json(response, 201, json);

    cJSON_Delete(json);
    macro_free(macro);
}

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

    const char *target_uid_str = args[0].value.v_str;

    uuid_t target_uid;
    if(uuid_parse(target_uid_str, target_uid))
    {
        M_RESPONSE_400_NO_VALID_ID(response);
        return;
    }

    macro_t* macro = macro_get_by_uid(target_uid);

    if(!macro)
    {
        M_RESPONSE_404_NO_MACRO_FOUND_FOR_ID(response);
        return;
    }

    if(macro_remove(macro))
    {
        M_RESPONSE_500_FAILED_TO_DELETE_FROM_DATABASE(response);
    }
    else
    {
        M_RESPONSE_MSG(LOGGER_DEBUG, response, 200, "deleted macro");
    }
    macro_free(macro);
}