/**
 * @file        main.c
 *
 * @brief       Main program body
 *
 * @version     V1.0.0
 *
 * @date        2023-12-01
 *
 * @attention
 *
 *  Copyright (C) 2023 Geehy Semiconductor
 *
 *  You may not use this file except in compliance with the
 *  GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE).
 *
 *  The program is only for reference, which is distributed in the hope
 *  that it will be useful and instructional for customers to develop
 *  their software. Unless required by applicable law or agreed to in
 *  writing, the program is distributed on an "AS IS" BASIS, WITHOUT
 *  ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions
 *  and limitations under the License.
 */

/* Includes ***************************************************************/
#include "main.h"

/* Private includes *******************************************************/
#include "apm32f4xx_device_cfg.h"
#include "fatfs.h"
#include "log.h"

/* Private macro **********************************************************/

/* Private typedef ********************************************************/

/* Private variables ******************************************************/
static const char* tag = "main";

/* FatFS */
FATFS fatfs;
FIL file;
FIL fileR;
DIR dir;
FILINFO fno;
FRESULT res;
BYTE buffer[FF_MAX_SS];
char DiskPath[4];

/* Private function prototypes ********************************************/

/* External variables *****************************************************/
extern FATFS* fs[FF_VOLUMES];

/* External functions *****************************************************/

/**
 * @brief   Main program
 *
 * @param   None
 *
 * @retval  None
 */
int main(void)
{
    /* Device configuration */
    DAL_DeviceConfig();

    res = f_mount(&fatfs, FATFS_GetDrivePath(SD_DISK), 1U);
    
    if (res == FR_NO_FILESYSTEM)
    {
        LOGW(tag, "The SD card is not formatted\r\n");
        
        LOGI(tag, "Formatting...\r\n");
        
        /* Start format SD card */
        res = f_mkfs((TCHAR const*)FATFS_GetDrivePath(SD_DISK), 0U, buffer, sizeof(buffer));

        if (res == FR_OK)
        {
            /* Cannel mount */
            res = f_mount(NULL, FATFS_GetDrivePath(SD_DISK), 1U);
            
            /* Mount again */
            res = f_mount(&fatfs, FATFS_GetDrivePath(SD_DISK), 1U);
        }
        else
        {
            LOGE(tag, "Formatting failed\r\n");
        }
    }

    if (res != FR_OK)
    {
        LOGE(tag, "Failed to mount SD card file system\r\n");
    }
    else
    {
        LOGI(tag, "SD card file system mounted ok\r\n");

        FATFS_WriteFile(&file, FATFS_GetDrivePath(SD_DISK));
        FATFS_ReadFile(&file, FATFS_GetDrivePath(SD_DISK));
    }

    /* Infinite loop */
    while (1)
    {
        BOARD_LED_Toggle(LED2);
        DAL_Delay(500U);
    }
}
