#include "Array.h"
#include "Types.h"
#include "GlobalArena.h"
#include <stdlib.h>
#include <string.h>

struct ArrayMeta {
    BumpArena b;
    usize element_size;
    usize count;
    usize length;
};

static inline struct ArrayMeta*
A_metadata(void* arr) {
    return arr - sizeof(struct ArrayMeta);
}

typedef void* Array;

Array
A_new(BumpArena b, usize element_size, usize length) {
    if (NULL == b)
        return NULL;

    struct ArrayMeta am = {
        .b = b,
        .element_size = element_size,
        .count = 0,
        .length = length,
    };

    void* start = B_alloc(b, sizeof(am) + element_size * length);
    memcpy(start, &am, sizeof(am));
    return start + sizeof(am);
}

usize
A_length(Array arr) {
    if (NULL == arr)
        return 0;
    return A_metadata(arr)->length;
}

usize
A_count(Array arr) {
    if (NULL == arr)
        return 0;
    return A_metadata(arr)->count;
}

Result
A_push(Array arr, void *value) {
    if (NULL == arr)
        return R_Uninitialized;

    struct ArrayMeta *am = A_metadata(arr);

    if (am->count >= am->length) {
        if (!B_resizeable(am->b, arr))
            return R_OutOfBounds;
        RETURN_NOTOK(B_resize(am->b, sizeof(*am) + am->element_size * (am->length <<= 1)));
    }

    memcpy(arr + am->count++ * am->element_size, value, am->element_size);

    return R_Ok;
}

Result
A_ppush(Array arr, void *pvalue) {
    void* temp = pvalue;
    return A_push(arr, &temp);
}

void*
A_pop(Array arr) {
    if (NULL == arr)
        return NULL;

    struct ArrayMeta *am = A_metadata(arr);

    if (am->count == 0)
        return NULL;

    return arr + am->element_size * --am->count;
}

Array
AG_new(usize element_size, usize length) {
    return A_new(g_arena, element_size, length);
}
