#include <desc.h>
#include <filereader.h>
#include <path_defs.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <system.h>

int filereader_init (struct filereader* fw, const char* volume, const char* path) {
  memset (fw, 0, sizeof (*fw));
  strncpy (fw->volume, volume, VOLUME_MAX);
  strncpy (fw->path, path, PATH_MAX);

  int ret;
  struct desc desc;

  if ((ret = volume_open (fw->volume)) < 0)
    return -FR_VOLUME_OPEN_ERROR;

  if ((ret = describe (fw->path, &desc)) < 0) {
    volume_close ();
    return -FR_DESC_ERROR;
  }

  if (desc.type != FS_FILE)
    return -FR_NOT_FILE;

  fw->file_size = desc.size;
  fw->flags |= FR_OPEN;

  return FR_OK;
}

int filereader_fini (struct filereader* fw) {
  if ((fw->flags & FR_OPEN)) {
    volume_close ();
    fw->flags &= ~FR_OPEN;
  }

  return FR_OK;
}

int filereader_read (struct filereader* fw, uint8_t* buffer, size_t buffer_size) {
  if (!(fw->flags & FR_OPEN))
    return -FR_VOLUME_NOT_OPENED;

  int ret;

  if (buffer_size > 0) {
    if (!(fw->read_cursor + buffer_size <= fw->file_size))
      return -FR_CURSOR_OOB;

    if ((ret = read_file (fw->path, fw->read_cursor, buffer, buffer_size)) < 0)
      return -FR_READ_ERROR;

    fw->read_cursor += buffer_size;
  }

  return FR_OK;
}
