/** 
 * @file    fs.h
 * @brief   File system using non-volatile external memory.
 * @author  Kenny Tran
 * @date    Mar 04 2024
 * @version 0.0.1
 *
 * @section LICENSES
 * Copyright (C) Morgan Advanced Programmable Systems, Inc.
 */


#ifndef FS_H_
#define FS_H_


/*--------------------------------------------------------------------------------------------------
 * INCLUDE FILES
 *------------------------------------------------------------------------------------------------*/
#include <stdint.h>

#include "../lib/errno.h"

#include "../bsp/nvm_ext.h"


/*--------------------------------------------------------------------------------------------------
 * MACROS & CONSTANTS
 *------------------------------------------------------------------------------------------------*/
#define FS_SECTOR_SIZE         (NVM_EXT_BLOCK_SIZE_4KB)
/**
 * @brief Size of the index written after each file entry.
 */
#define FS_FILE_INDEX_SIZE     (sizeof (uint32_t))
/**
 * @brief Size of checksum written after each file entry and index.
 */
#define FS_FILE_CHECKSUM_SIZE  (sizeof (uint32_t))
/**
 * @brief Max amount of characters in the filename.
 */
#define FS_FILENAME_LEN        (16)
/**
 * @brief Max file entry size, accounting for the appended index and checksum.
 */
#define FS_MAX_FILE_ENTRY_SIZE (FS_SECTOR_SIZE - FS_FILE_INDEX_SIZE - FS_FILE_CHECKSUM_SIZE)
/**
 * @brief Max amount of files to be created / stored.
 */
#define FS_MAX_FILES           (16)
/**
 * @brief Max amount of entries per file.
 */
#define FS_MAX_FILE_ENTRIES    (0xFFFFFFFF)
/**
 * @brief Default file depth
 */
#define FS_FILE_DEPTH_DEFAULT  (16)


/*--------------------------------------------------------------------------------------------------
 * TYPE DEFINITIONS & ENUMERATIONS
 *------------------------------------------------------------------------------------------------*/
/**
 * @brief Used as the file handle.
 */
typedef void* FS_file_t;


/*--------------------------------------------------------------------------------------------------
 * PUBLIC FUNCTION PROTOTYPES
 *------------------------------------------------------------------------------------------------*/
ERRNO_e FS_init (void);

ERRNO_e FS_open_or_create (char *p_filename, FS_file_t *p_file, uint16_t size, uint16_t depth);

ERRNO_e FS_write (FS_file_t file, uint8_t *p_src);

ERRNO_e FS_write_at_offset (FS_file_t file, uint8_t *p_src, uint16_t offset, uint16_t len);

ERRNO_e FS_read (FS_file_t file, uint8_t *p_dest, uint16_t offset, uint16_t len);

ERRNO_e FS_clear (FS_file_t file);

ERRNO_e FS_delete (char *p_filename);

uint32_t FS_memory_used (void);

uint32_t FS_memory_available (void);

void FS_cli_cmd (int32_t argc, char **argv);


#endif /* FS_H_ */
