/*
 * SD_Card.h
 *
 *  Created on: 24 дек. 2021 г.
 *      Author: Николай
 */

#ifndef INC_SD_CARD_H_
#define INC_SD_CARD_H_

#include "GSM.h"
#include "fatfs.h"
//FATFS

#define __MIN_FREE_SPACE_REQUIRED 500*1000*1000 //bytes

FATFS FatFs; 	//Fatfs handle
FIL fil; 		//File handle
FRESULT fres; //Result after operations
DIR dir;

FILINFO flinf;
DWORD free_clusters, free_sectors, total_sectors;
uint32_t free_space;
FATFS* getFreeFs;
UINT nRead;
char readbuff[1024];
uint32_t sizeWritten;
unsigned int BytesWr;

typedef enum{
	SD_OP_DONOTHING,
	SD_OP_WRITE_STATUS,
	SD_OP_WRITE_PARAM,
	SD_OP_WRITE_HEADER,
	SD_OP_DELETEOLD,
	SD_OP_MOUNT,
	SD_OP_UMOUNT
}SD_Op_Commands;

typedef enum{
	SD_READY,
	SD_BUSY,
	SD_ERROR,
	SD_COMMAND_SET,
	SD_COMMAND_NOT_SET
}SD_Card_states;

typedef enum{
	SD_IDLE,
	SD_MOUNT,
	SD_OPEN_DIR,
	SD_OPEN_FILE,
	SD_WRITE,
	SD_WRITE_HEADER,
	SD_READ,
	SD_CLOSE,
	SD_UMOUNT,
	SD_DELETE_OLD_FILES,
	SD_CHECK_FREE_SPACE

} SD_Stages;

typedef struct{
	uint64_t Battery_Serial;
	HTTP_DATA_Struct CSV_DATA;
	Battery_Data_Struct BATTERY_DATA;
	char Raw_var[100];
	SD_Op_Commands SD_Active_Command;
	SD_Card_states SD_State_to_return;
	SD_Stages SD_Stages_list;

	uint8_t SD_CARD_ChipDetect;
	char* DATA0;
	char DATA0_ch[1000];

	char* Header;
	char* FileName;
	char* Path;
	char Path_ch[100];
	char Filename_ch[20];
	uint8_t Mount_Flag;
	uint8_t Mount_CMD_SET;

	uint8_t Filename_Check_Done;

	FRESULT Fat_result;
}SD_CARD_Global_Struct;

typedef struct{
	char isDir;

	char fullpath_ch[100];
	char* fullpath;
	char filename_ch[13];
	char* filename;
	uint32_t value;

	uint32_t FN_Value;
	uint8_t Lastfound_FN_Month;
	uint8_t Lastfound_FN_Year;
	uint8_t Oldest_FN_Month;
	uint8_t Oldest_FN_Year;
	uint32_t Oldest_FN_Value;

}ff_search_struct;


void Battery_Data_to_CSV_Converter(SD_CARD_Global_Struct* Sd_Struct, HTTP_DATA_Struct* DST);
void CSV_Status_Data_Compilation(SD_CARD_Global_Struct* Sd_Struct);
void CSV_Param_Data_Compilation(SD_CARD_Global_Struct* Sd_Struct);
SD_Card_states SD_Set_Command(SD_CARD_Global_Struct* SD_Struct, SD_Op_Commands CMD, uint32_t Timeout);
void SD_Card_Processing(SD_CARD_Global_Struct* SD_Struct);
uint64_t Filename_to_Value(char* FN);
uint8_t Configure_Path_to_delete(char* path, uint32_t Value);
void Search_for_Oldest(volatile ff_search_struct* sourceStruct,char* Path, uint64_t ActualSerial);
void SD_Update_Path(SD_CARD_Global_Struct* source);

#endif /* INC_SD_CARD_H_ */
