#include <stddef.h>
#include <stdint.h>
#include "spinlock/spinlock.h"
#include "errors.h"
#include "dlmalloc/malloc.h"
#include "ramsd.h"
#include "storedev.h"
#include "hal/hal.h"
#include "util/util.h"
#include "kprintf.h"

int32_t ramsd_init(struct StoreDev *sd, void *extra) {
  RamSdInitExtra *e = extra;
  sd->sd.ramsd.capacity = e->capacity;
  if (e->preallocbuffer != NULL) {
    sd->sd.ramsd.buffer = e->preallocbuffer;
  } else {
    sd->sd.ramsd.buffer = dlmalloc(sd->sd.ramsd.capacity);
    if (sd->sd.ramsd.buffer == NULL) {
      return E_NOMEMORY;
    }
  }
  return E_OK;
}

int32_t ramsd_read(struct StoreDev *sd, uint8_t *const buffer, ptrdiff_t sector, ptrdiff_t off, size_t size) {
  RamSd *ramsd = &sd->sd.ramsd;
  spinlock_acquire(&sd->spinlock);
  hal_memcpy(buffer, ramsd->buffer + (sector * sd->sectorsize + off), size);
  spinlock_release(&sd->spinlock);
  return E_OK;
}

int32_t ramsd_write(struct StoreDev *sd, const uint8_t *const buffer, ptrdiff_t sector, ptrdiff_t off, size_t size) {
  RamSd *ramsd = &sd->sd.ramsd;
  spinlock_acquire(&sd->spinlock);
  hal_memcpy(ramsd->buffer + (sector * sd->sectorsize + off), buffer, size);
  spinlock_release(&sd->spinlock);
  return E_OK;
}

int32_t ramsd_cleanup(struct StoreDev *sd) {
  spinlock_acquire(&sd->spinlock);
  dlfree(sd->sd.ramsd.buffer);
  spinlock_release(&sd->spinlock);
  return E_OK;
}

size_t ramsd_capacity(struct StoreDev *sd) {
  size_t capacity;
  spinlock_acquire(&sd->spinlock);
  capacity = sd->sd.ramsd.capacity;
  spinlock_release(&sd->spinlock);
  return capacity;
}
