#include "jes.h"
#include "jes/FileReader.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

namespace jes
{
    bool FileReader::load(const char * fname, uint8_t ** buf, size_t * size)
    {
        struct stat st;
        if (stat(fname, &st) != 0)
        {
            return false;
        }

        if (st.st_size < 0)
        {
            return false;
        }

        *size = st.st_size;
        if (st.st_size == 0)
        {
            return true;
        }

        int fd = open(fname, O_RDONLY | JES_O_BINARY);
        if (fd < 0)
        {
            return false;
        }

        *buf = new uint8_t[st.st_size];

        off_t n_bytes_read = 0u;
        for (;;)
        {
            off_t rd_size = read(fd, &(*buf)[n_bytes_read], st.st_size - n_bytes_read);
            if (rd_size <= 0)
                break;
            n_bytes_read += rd_size;
            if (n_bytes_read >= st.st_size)
                break;
        }
        if (n_bytes_read != st.st_size)
        {
            delete[] *buf;
            *buf = NULL;
            close(fd);
            return false;
        }

        close(fd);

        return true;
    }
}
