//  Copyright (C) 2016, mituhiromatuura all right reserved.

#include <stdio.h>
#include <string.h>
#include <kernel.h>

#include "disp.h"
#include "fatfs.h"
#include "index.h"
#include "lcd.h"
#include "save_jpg.h"
#include "wait.h"

extern void write_JPEG_file (FIL *fobjp, int quality);
volatile int filenum = 1;

void save_jpg(void)
{
	if(0 != (disk_initialize(0) & (STA_NOINIT | STA_NODISK)))goto error;

	FIL fobj;
	FRESULT res;

	res = fatfs_mount(&fatfs, "", 0);
	if(FR_OK != res)goto error;

	char filename[8+1+3+1];

	while(1)
	{
		sprintf(filename, "%d.jpg", filenum);
		if(FR_NO_FILE == fatfs_stat(filename, NULL))
		{
			break;
		}
		filenum++;
	}

	res = fatfs_open(&fobj, filename, FA_WRITE | FA_CREATE_NEW);
	if(FR_OK != res)goto error;

	display_read_set_m(0, 0, 240 - 1, 320 - 1);

	lcd_wr_cmd(0x0020);lcd_wr_data(0x0000); // GRAM horizontal Address
	lcd_wr_cmd(0x0021);lcd_wr_data(0x0);//13F); // GRAM Vertical Address
	lcd_wr_cmd(0x0022);

	lcd_rd_data();
	lcd_rd_data();

	write_JPEG_file(&fobj, QUALITY);

	display_area_set_m(0, 0, 240 - 1, 320 - 1);

	fatfs_close(&fobj);
	index_add(filenum++);
	lcd_puts(LCD_LEFT, 4, filename, FCOLOR, BCOLOR);
	wait_busy(1000);
	return;

error:
	lcd_puts(3, 2, "error", FCOLOR, BCOLOR);
	wait_busy(1000);
	return;
}
