/** 
 * \file fat32.h
 * \brief FAT32 header file
 * \details File contains structures, enumerations and functions declarations for FAT32 app
 *
 * \author Juraj Golej
 * \version 1.0
 */


#ifndef FAT32_H_
#define FAT32_H_

#include <drivers/sdcard/sdcard.h>
#include <string.h>
#include "fat32_cfg.h"

/** 
 * \brief FAT32 file structure
 */
struct FAT32_file {
	char name[9];		///< File name (8.3 type)
	char extension[3];	///< File extension (8.3 type)
	uint32_t ID;		///< File ID (cluster number)
	uint32_t size;		///< FIle size in bytes
}; /* struct FAT32_file */

/** 
 * \brief FAT32 application structure
 */
struct FAT32_app {
	uint32_t bootAddress_ABS;			///< Boot address in absolute sectors
	uint32_t fatAddress_LBA;			///< First FAT address in sectors (from boot sector)
	uint32_t dataAdress_LBA;			///< Data area address in sectors (from boot sector)

	uint16_t clusterSize;				///< Cluster size (in sectors)
	uint32_t rootCluster;				///< Root cluster number in data area (in clusters)

	uint32_t currentCluster;			///< Actual cluster
	uint8_t buffer[FAT32_SECTOR_SIZE];	///< Read data buffer
	uint16_t bufferIndex;				///< Actual read index in buffer
	uint16_t sectorIndex;				///< Actual sector index in cluster

	uint32_t fileSize;					///< Opened file size
}; /* struct FAT32_app */

/**
 * \brief Initialize application
 * 
 * \return \b enum \b retCode Return code value
 * \retval ENone everything OK
 * \retval EDenied Problem in initialization process
 *
 * \note Call this function before anything else
 */
enum retCode FAT32_init();

/**
 * \brief Load the first root sector
 * 
 * \return \b enum \b retCode Return code value
 * \retval ENone everything OK
 * \retval EHardwareProblem Can't read from SD card
 */
enum retCode FAT32_goToRoot();

/**
 * \brief Get next file from root 
 * 
 * \param[in] extension File extension filter
 * \param[out] file Pointer on \c FAT32_file structure
 *
 * \return \b enum \b retCode Return code value
 * \retval ENone everything OK
 * \retval EDenied Can't get next file (it was the last)
 * \retval EEof This is the last sector
 */
enum retCode FAT32_nextFile(const char* extension, struct FAT32_file* file);

/**
 * \brief Open selected file and load first sector
 * 
 * \param[in] file Pointer on \c FAT32_file structure
 *
 * \return \b enum \b retCode Return code value
 * \retval ENone everything OK
 * \retval EDenied Can't load next sector (maybe it was the last)
 * \retval EHardwareProblem Can't read from SD card
 * \retval EEof This is the last sector
 */
enum retCode FAT32_file_open(struct FAT32_file* file);

/**
 * \brief Read one line from file
 * 
 * \param[out] str Pointer on read buffer
 * \param[in] maxlen Maximum bytes that can be read
 *
 * \return \b int16_t Number of read bytes or -1, if EOF
 */
int16_t FAT32_read(uint8_t* str, const uint16_t maxlen);

#endif /* FAT32_H_ */