#include <cstdio>
#include <cstdint>

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


static const char* const TAG = "MAIN";
static constexpr uint16_t delay_ms = 5000;
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);

		// Calculating worse stack allocation
		TX_THREAD* current_thread = tx_thread_identify();
		printf("%s: Stack size: %lu, used: %u, free: %u\n", TAG, current_thread->tx_thread_stack_size,
			   (uint8_t*)current_thread->tx_thread_stack_ptr - (uint8_t*)current_thread->tx_thread_stack_start,
			   (uint8_t*)current_thread->tx_thread_stack_end - (uint8_t*)current_thread->tx_thread_stack_ptr);

	}
}
