#include <fat.h>
#include <sdcard/gcsd.h>
#include <sdcard/wiisd_io.h>
#include <string.h>
#include <unistd.h>

#include "fat.h"

/* FAT device */
fatDevice *fdev = NULL;

/* FAT device list  */
fatDevice fdevList[] = { { "sd", "Wii SD Slot", &__io_wiisd }, { "usb",
    "USB Mass Storage Device", &__io_usbstorage }, { "smb", "SMB Share",
    &__io_wiisd }, { "gcsda", "SD Gecko (Slot A)", &__io_gcsda }, { "gcsdb",
    "SD Gecko (Slot B)", &__io_gcsdb }, };

#define NB_FAT_DEVICES_PPD      (sizeof(fdevList) / sizeof(fatDevice))

const int NB_FAT_DEVICES = NB_FAT_DEVICES_PPD;

void SDCard_deInit() {
    //closing all open Files write back the cache and then shutdown em!
    fatUnmount("SD:/");
    __io_wiisd.shutdown();
}

int SDCard_Init() {
    SDCard_deInit();
    return fatMountSimple("sd", &__io_wiisd);
}

int USBDevice_Init() {
    int retry = 0;
    s32 fatMounted = 0;
    while (!fatMounted && (retry < 15)) {
        fatMounted = fatInitDefault();
        sleep(1);
        retry++;
    }
    return fatMounted;
}

s32 Fat_Mount(fatDevice *dev) {
    s32 ret;

    // Initialize interface
    ret = dev->interface->startup();
    if (!ret) return -1;

    // Mount device
    ret = fatMountSimple(dev->mount, dev->interface);

    if (!ret) return -2;

    return ret;
}

void Fat_Unmount(fatDevice *dev) {
    if (strncmp(dev->mount, "usb", 3) != 0) {
        // Unmount device
        fatUnmount(dev->mount);

        // Shutdown interface
        dev->interface->shutdown();
    }
}
