#include <pico/stdlib.h>
#include <pico/stdio.h>
#include <stdio.h>
#include <pico/platform.h>
#include <ff.h>
#include <string.h>
#include "types.h"

DWORD get_fattime() {
    return 0;
}

int main(void) {
    stdio_init_all();

    FATFS fs;
    FIL fp;
    DIR dp;
    FILINFO fi;
    FRESULT res;

    if (FR_OK != (res=f_mount(&fs, "", 0))) {
        printf("f_mount failed, %d.\n", (i32)res);
    }

    if (FR_OK != (res=f_opendir(&dp, "/"))) {
        printf("f_opendir failed, %d.\n", (i32)res);
    }

    for (;;) {
        if (FR_OK != (res=f_readdir(&dp, &fi)) || 0 == fi.fname[0]) {
            break;
        }
        printf("file: %s, %d Bytes\n", fi.fname, fi.fsize);
    }

    if (FR_OK != res) {
        printf("f_readdir failed, %d.\n", (i32)res);
    }

    char buf[4096];
    UINT br, br_acc=0, bw;

    if (FR_OK != (res=f_open(&fp, "/config.txt", FA_READ))) {
        printf("f_open failed, %d.\n", (i32)res);
    } else {
        for (;;) {
            f_read(&fp, buf, 4096, &br);
            br_acc += br;
            if (0 == br) {
                break;
            }
        }
        f_close(&fp);
    }

    if (FR_OK != (res=f_open(&fp, "/write.txt", FA_WRITE | FA_CREATE_ALWAYS))) {
        printf("f_open failed, %d.\n", (i32)res);
    } else {
        if (FR_OK != (res = f_write(&fp, buf, br_acc, &bw))) {
            printf("f_write failed, %d.", (i32)res);
        }
        printf("bw: %d.\n", (i32)bw);
        f_close(&fp);
    }

    if (FR_OK != (res=f_unmount(""))) {
        printf("f_unmount failed, %d.\n", (i32)res);
    }

    while (1) {
        tight_loop_contents();
    }

    return 0;
}
