#include "ff.h"
#include "sd.h"
#include "sdio_sd.h"
#include "device.h"

#define RETRY_MAX (3)

FATFS fs;
TCHAR file_name[FILE_NAME_LEN];

uint8_t sd_detect(void)
{
    SD_Error sd_err;
    FRESULT ret;
    uint32_t retry;
    DIR dir;
    TCHAR name[FILE_NAME_LEN];

    retry = RETRY_MAX;
    while (retry--) {
        sd_err = SD_Init();
        if (sd_err == SD_OK) {
            break;
        } else if (retry == 0) {
            SD_DeInit();
            return SD_STS_ERR_INIT;
        }
    }
    
    retry = RETRY_MAX;
    while (retry--) {
        ret = f_mount(0, &fs);
        if (ret == FR_OK) {
            break;
        } else {
            SD_DeInit();
            return SD_STS_ERR_MOUNT;
        }
    }

    retry = RETRY_MAX;
    while (retry--) {
        ret = f_getcwd(name, sizeof(name));
        if (ret == FR_OK) {
            break;
        } else {
            SD_DeInit();
            return SD_STS_ERR_GETCWD;
        }
    }

    retry = RETRY_MAX;
    while (retry--) {
        ret = f_opendir(&dir, name);
        if (ret == FR_OK) {
            break;
        } else {
            SD_DeInit();
            return SD_STS_ERR_OPENDIR;
        }
    }

    return SD_STS_OK;
}

void sd_loop(void)
{
    static uint32_t ms = 0;

    if (system_tick_cnt < (ms + 500)) {
        return;
    }
    ms = system_tick_cnt;

    device_data.sd = sd_detect();
}
