#include "arc/audio/config.h"

#include "audio.h"
#include <stdlib.h>
#include "arc/std/config.h"
#include "arc/std/errno.h"
#include "arc/audio/audio.h"

// #define ARC_DEFAULT_CONFIG
#include "arc/std/defaults/config.h"

void ARC_AudioConfig_Init(ARC_Config *config){
    ARC_Config_AddKeyCString(config, (char *)"ARC_Audio", 9, ARC_Audio_Read, ARC_Audio_Delete);
}

uint8_t ARC_Audio_Read(ARC_Config *config, ARC_String *string, void **value){
    ARC_Config_Get(config, string, value);
    if(*value){
        return 1;
    }

    if(string->data[0] != '"' || string->data[string->length - 1] != '"'){
        ARC_DEBUG_LOG_ERROR_WITH_VARIABLES("in ARC_Point_Read(config, string, value); no matching quotes: %s", string->data);
        arc_errno = ARC_ERRNO_DATA;
        return 0;
    }

    ARC_Audio *audio = (ARC_Audio *)malloc(sizeof(ARC_Audio));

    ARC_String *path;
    ARC_String_CopySubstring(&path, string, 1, string->length - 2);
    audio->chunk = Mix_LoadWAV(path->data);

    //TODO: get error message if not loaded

    *value = (void *)audio;
    return 0;
}

void ARC_Audio_Delete(ARC_Config* config, ARC_String *string, void *value){
    Mix_FreeChunk(((ARC_Audio *)value)->chunk);
    free((ARC_Audio *)value);
}