#include <cstdio>
#include <cstdint>

#include "tx_api.h"
#include "fx_api.h"
//#include "main.h"
#include "main_thread.h"

static constexpr uint16_t delay_ms = 500;	// Must be greater than 10ms
static constexpr unsigned MAX_CHARS_IN_VOLUME_NAME = 12U;
static CHAR volumeName[MAX_CHARS_IN_VOLUME_NAME];
static CHAR entry[FX_MAX_LONG_NAME_LEN];
UINT ret;

void startMainThread(FX_MEDIA* sdio_disk)
{
	ret = fx_media_volume_get(sdio_disk, volumeName, FX_DIRECTORY_SECTOR);
	if (ret == FX_SUCCESS)
	{
		printf("Volume label: %s\n", volumeName);

		ULONG64 available_bytes = 0;
		ret = fx_media_extended_space_available(sdio_disk, &available_bytes);
		if (ret == FX_SUCCESS)
		{
			printf("Free space: ");
			[available_bytes]
			{
				constexpr unsigned EXT_NUM = 5U;
				char ext[EXT_NUM][6] { "bytes", "KB", "MB", "GB", "TB"};
				char fmt[] {"%llu %s\n"};

				for (auto i = 0U; i < EXT_NUM; i++)
				{
					uint64_t limit = 1ULL << (10U * (i + 1U));
					if (available_bytes < limit)
					{
						printf(fmt, available_bytes / (limit >> 10U) , ext[i]);
						return;
					}
				}
				printf(fmt,  available_bytes/ (1ULL << (10U * 5U)));
			}();

			ret = fx_directory_first_entry_find(sdio_disk, entry);
			while(ret == FX_SUCCESS)
			{
				ret = fx_directory_name_test(sdio_disk, entry);
				if (ret == FX_SUCCESS)
				{
					printf("Found folder: %s\n", entry);
				}
				ret = fx_directory_next_entry_find(sdio_disk, entry);
			}
		}
	}
	else
	{
		printf("Disk name cannot be obtained!\n");
	}


	while(1)
	{
		tx_thread_sleep(delay_ms);
	}
}
