#include "custom_receive_and_write.h"
extern UART_HandleTypeDef huart3;
struct flags flags_UART_FATFS;
extern FIL SDFile;
uint8_t bytescnt;
char Char_Shift = 0x41;
FIL MFile;

uint8_t Message[sizebuff] = "";

uint8_t path_uart[5] = "A.txt";


//void MountSD(void)
//{
//	if((f_mount(&SDFatFS, (TCHAR const*)SDPath, MOUNT)) ==FR_OK)
//  {
//		for (int i=0;i<5;i++)
//			{
//				GPIOB->ODR^=1<<14;
//				HAL_Delay(500);
//			}
//			 GPIOB->ODR&=~(1<<14);  \
//	}
//}

FRESULT CreateAndOpenMessageFile(FIL *MessageFile, const TCHAR* Path)
{
	return f_open(MessageFile, Path, FA_WRITE | FA_CREATE_ALWAYS);
}

FRESULT OpenMessageFile(FIL *MessageFile, const TCHAR* Path)
{
	return f_open(MessageFile, Path, FA_READ);
}

FRESULT WriteMessage(FIL *MessageFile, char *Message, UINT SizeOfMessage)
{
	FRESULT ResultOfOperation;
	uint32_t WrittenBytes;
	ResultOfOperation = f_lseek(MessageFile,f_size(MessageFile));
	ResultOfOperation = f_write(MessageFile, Message, SizeOfMessage, &WrittenBytes);
	if (WrittenBytes!=SizeOfMessage) return FR_INVALID_PARAMETER;
	//GPIOB->ODR^=0xf000;
	return ResultOfOperation;
}

FRESULT CloseMessageFile(FIL *MessageFile)
{
	return f_close(MessageFile);	
}

void WriteFile(char *Data, int Num_of_Data)
{ 
	static int FileOpen = 0;
	OpenMessageFile(&MFile, (const TCHAR*)path_uart);
	WriteMessage(&MFile, Data, Num_of_Data);
	CloseMessageFile(&MFile);
//	Char_Shift++;
//	path_uart[0] = (char)Char_Shift;
}

void Check_USART(void)
{		
	uint8_t res;

	static FIL MessageFile;

	if (flags_UART_FATFS.writting==0)
	{		switch((int)Message[0])
		{
			case 1:			
			flags_UART_FATFS.writting = 1;
			Message[bytescnt] = '\0';
			res = CreateAndOpenMessageFile(&MessageFile, (const TCHAR*)(Message+1)); 
			break;
			case 2:		
			flags_UART_FATFS.writting = 1;
			res = OpenMessageFile(&MessageFile, (const TCHAR*)path_uart);	
			break;	
		}	

	}
	else
	{		
		if (Message[0] == 0x03)
		{
			flags_UART_FATFS.writting = 0;
			res = CloseMessageFile(&MessageFile);
		}		
		else 
		{
			res = WriteMessage(&MessageFile, (char *)Message, bytescnt);
		}
	}
	HAL_UART_AbortReceive_IT(&huart3);
	HAL_UART_Receive_IT(&huart3, Message, sizeof(Message));
	

	bytescnt = 0;
	for(int i = 0; i<sizebuff; i++)
	{
		Message[i] = 0x00;
	}
}
