#include "ff_Macros.h"
#include "lcd.h"
#include "sd_spi_stm32.h"

extern u8 buf[12],text[60];
u8 LFF_Y=2,LFF_X=85; //LCD Fat FS Offsets
u8 FF_Path[255]= "";
FRESULT ff_res;
FATFS fatfs;
FIL file;

void ff_remove(char* filepath) {
	ff_LCD_FRESULT(LFF_X,LFF_Y,"f_unlink:",f_unlink(filepath)); LFF_Y+=8;
	ff_LCD_Text(LFF_X,LFF_Y,"...auto read Disk:","",LCD_Red); LFF_Y+=8;
	strcpy(FF_Path,"");
	ff_DiscFindFiles(FF_Path);
}
void ff_TxtWrite(char* filepath, char* input, char WriteMode) {
    FRESULT fr;    /* FatFs return code */
	UINT cnt=0;
	char *inf=text,len=0;
	
	SPI_SelectDevice(1); //0=off 1=SD 2=TP
    /* Open a text file */
    fr = f_open(&file, filepath, FA_OPEN_ALWAYS|FA_WRITE); //erstellen wenn nicht da
    if (fr) {
		ff_LCD_Text(LFF_X,LFF_Y,"Open:",filepath,LCD_Red); LFF_Y+=8;
		ff_LCD_FRESULT(LFF_X,LFF_Y," ERR:",fr); LFF_Y+=8;
		return;
	} else {
		ff_LCD_Text(LFF_X,LFF_Y,"Open:",filepath,LCD_Green); LFF_Y+=8;
	}
	if (WriteMode!=ff_WrMode_Override) {
		f_lseek(&file,f_size(&file)); //mit: am ande anfügen, ohne: anfang überschreiben
	}
	
    /* format and write Line */
	if (WriteMode==ff_WrMode_AddNewLine) {
		strcpy(text,"\r\n"); strcat(text,input);
	} else {
		strcpy(text,""); strcat(text,input);
	}
	
	while (*inf++) { len++; } //herrausfinden, wie lang der String ist (sizeof(text) gibt nur die größe des ganzen Arrays)
	ff_LCD_Text(LFF_X,LFF_Y,"zu schreibender Text: ",text,LCD_Yellow); LFF_Y+=8;
	ff_LCD_FRESULT(LFF_X,LFF_Y,"f_write: ",f_write(&file,&text,len,&cnt)); LFF_Y+=8;
	strcpy(text,""); itoa(cnt, buf, 10); strcat(text,buf);
	ff_LCD_Text(LFF_X,LFF_Y,"geschriebene Zeichen: ",text,LCD_Yellow); LFF_Y+=8;
	
	/* file info */
	strcpy(text,""); itoa(f_size(&file), buf, 10); strcat(text,buf); strcat(text," Bytes");
	ff_LCD_Text(LFF_X,LFF_Y,"file size now: ",text,LCD_Green); LFF_Y+=8;
	
    f_close(&file);
}
void ff_TxtRead(char* filepath) {
    char line[46]; /* Line buffer */
    FRESULT fr;    /* FatFs return code */
	char cnt=0;
	
	SPI_SelectDevice(1); //0=off 1=SD 2=TP
    /* Open a text file */
    fr = f_open(&file, filepath, FA_READ);
    if (fr) {
		ff_LCD_Text(LFF_X,LFF_Y,"Open:",filepath,LCD_Red); LFF_Y+=8;
		ff_LCD_FRESULT(LFF_X,LFF_Y," ERR:",fr); LFF_Y+=8;
		return;
	} else {
		ff_LCD_Text(LFF_X,LFF_Y,"Open:",filepath,LCD_Green); LFF_Y+=8;
	}
    /* Read all lines and display it */
    while (f_gets(line, sizeof line, &file)) {
		if (line[0]==0) { continue; } //leere Zeilen überspringen		
		ff_LCD_Text(LFF_X,LFF_Y,"",line,LCD_White);
		ff_LCD_Text(309,LFF_Y,"\r\n","",0); //damit neue Zeilen auf dem uart ausgegeben werden
		LFF_Y+=8; cnt++;
		if (cnt==20) {
			ff_LCD_Text(LFF_X,LFF_Y,"","\r\n...19 (oder mehr) Zeilen -> Vorzeitiges ENDE",LCD_Green); LFF_Y+=8;
			f_close(&file); return;
		}
	}
	ff_LCD_Text(LFF_X,LFF_Y,"","\r\n####End of File###",LCD_Green); LFF_Y+=8;
    f_close(&file);

}
FRESULT ff_DiscFindFiles(char* path) {
	FRESULT res;
    FILINFO fno;
    DIR dir;
    int i;
	
    char *fn;   /* This function is assuming non-Unicode cfg. */
#if _USE_LFN
    static char lfn[_MAX_LFN + 1];   /* Buffer to store the LFN */
    fno.lfname = lfn;
    fno.lfsize = sizeof lfn;
#endif

	SPI_SelectDevice(1); //0=off 1=SD 2=TP
	
    res = f_opendir(&dir, path);                       /* Open the directory */
    if (res == FR_OK) {
        i = strlen(path);
		strcpy(text,path); strcat(text,"/"); //strcat(str,fn);
        for (;;) {
			
            res = f_readdir(&dir, &fno);                   /* Read a directory item */
            if (res != FR_OK || fno.fname[0] == 0) break;  /* Break on error or end of dir */
            if (fno.fname[0] == '.') continue;             /* Ignore dot entry */
#if _USE_LFN
            fn = *fno.lfname ? fno.lfname : fno.fname;
#else
            fn = fno.fname;
#endif
            if (fno.fattrib & AM_DIR) {                    /* It is a directory */
				sprintf(&path[i], "/%s", fn);
				ff_LCD_Text(LFF_X,LFF_Y,"DIR:",path,LCD_Green);
				ff_LCD_Text(309,LFF_Y,"\r\n","",0); LFF_Y+=8;
                res = ff_DiscFindFiles(path);
                if (res != FR_OK) break;
                path[i] = 0;
            } else {                                       /* It is a file. */
				ff_LCD_Text(LFF_X,LFF_Y,text,fn,LCD_Green);
				ff_LCD_Text(309,LFF_Y,"\r\n","",0); LFF_Y+=8;
            }
        }
        f_closedir(&dir);
    } else {
		ff_LCD_FRESULT(LFF_X,LFF_Y,"f_opendir:",res); LFF_Y+=8;
	}
}
/*******END OF FILE****/
