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

#include <kernel.h>
#include "kernel_cfg.h"
#include "iodefine.h"

#include "beep.h"
#include "bt.h"
#include "button.h"
#include "camera.h"
#include "disp.h"
#include "dma.h"
#include "exbus.h"
#include "exint.h"
#include "exti.h"
#include "gpio.h"
#include "index.h"
#include "lcd.h"
#include "mem.h"
#include "play.h"
#include "rec_avi.h"
#include "save_jpg.h"
#include "wait.h"

void setup()
{
	exint_camvs_init();
	init_exti();
	init_gpio();
	init_bt();
	init_exbus();
	init_display();
	init_mem();
	init_button();

	lcd_puts(LCD_CENTER, 1, "  SK-FM4  ", FCOLOR, BCOLOR);
	lcd_puts(LCD_CENTER, 3, " DriveRec ", FCOLOR, BCOLOR);

	init_dma();
	init_camera();
	irq_start();
}

void loop()
{
	static int camera_mode = 1;

	if(button_c_is_on())
	{
		int count = 0;
		while(button_c_is_on())
		{
			if(100 > count)
			{
				count++;
				dly_tsk(1);
			}
			else
			{
				beep();
				irq_stop();

				while(1)
				{
					if(0 == camera_mode)
					{
						lcd_puts(8, 0, "STILL", RED, WHITE);
						lcd_puts(0, 0, "MOVIE", BLACK, WHITE);
					}
					else
					{
						lcd_puts(8, 0, "STILL", BLACK, WHITE);
						lcd_puts(0, 0, "MOVIE", RED, WHITE);
					}
					lcd_puts(5, 2, "OK", WHITE, RED);
					while(button_a_is_on() || button_b_is_on() || button_c_is_on());

					while(!button_a_is_on() && !button_b_is_on() && !button_c_is_on());

					if(button_a_is_on())
					{
						beep();
						camera_mode = 0;
					}
					else
					if(button_b_is_on())
					{
						beep();
						camera_mode = 1;
					}
					else
					if(button_c_is_on())
					{
						break;
					}
				}
				irq_start();
				beep_long();
				while(button_a_is_on() || button_b_is_on() || button_c_is_on());
			}
		}
	}

	if(button_a_is_on() || button_hb_is_on())
	{
		if(0 == camera_mode)
		{
			beep();
			irq_stop_m();
			save_jpg();
			while(button_a_is_on() || button_b_is_on());
			irq_start();
		}
		else
		{
			beep();
			if(button_hb_is_on())hb_on = 1;
			rec_avi();
			while(button_a_is_on() || button_b_is_on());
		}
	}

	if(button_b_is_on())
	{
		beep();
		irq_stop();
		play();
		irq_start();
		while(button_a_is_on() || button_b_is_on());
	}

	static int sdcd_in = 0;
	if(button_sdcd_is_on())
	{
		if(!sdcd_in)
		{
			irq_stop();
			if(index_scan())
			{
				lcd_puts(LCD_LEFT, 4, "card in", FCOLOR, BCOLOR);
			}
			else
			{
				lcd_puts(LCD_LEFT, 4, "card error", FCOLOR, BCOLOR);
			}
			wait_busy(1000);
			irq_start();
		}
		sdcd_in = 1;
	}
	else
	{
		if(sdcd_in)
		{
			irq_stop();
			lcd_puts(LCD_LEFT, 4, "card out", FCOLOR, BCOLOR);
			wait_busy(1000);
			irq_start();
		}
		sdcd_in = 0;
	}
}
