///#include "main.h"
#include <time.h>
#include "renderer.h"
#include "sound.h"
#include "screen.h"
#include "pad.h"
#include "menu.h"

int pad_state;
int cur_time;
int now_sensor_x,now_sensor_y;
int bMenu=0;

const char *scr_names[] = {
	"x1",
	"x2",
	"x3",
};

void render_screen(void *buf)
{
	if (border_uploaded && sgb_mode){
		screen_bitblt_sgb(0, 0, sgb_border_buffer);
	}
	gb_screen_scale = setting.screensize + 1.0;
	screen_bitblt_gb((SGBWIDTH - GBWIDTH)/2,(SGBHEIGHT - GBHEIGHT)/2,(u16*)buf);
}

void renderer_update_sound()
{
	static unsigned int nextbank=1;
	unsigned int playbank=cur_play/SOUND_BANKLEN;
	if (nextbank!=playbank) {
		snd_render(&sound_buf[nextbank*SOUND_BANKLEN/2],SOUND_BANKLEN/4);
		nextbank=((nextbank+1)&3);
	}
}

#define UPPER_THRESHOLD  0xcf
#define LOWER_THRESHOLD  0x2f
void renderer_update_pad()
{
	int pstate = pad_menu_buttons();
	pad_state = pad_game_buttons();
	
	
	if(pstate & GB_MENU)
		bMenu = 1;
	if(pstate & GB_CHANGE_SIZE){
		setting.screensize = (setting.screensize+1)%3;
		screen_clear();
	}
}

void renderer_refresh()
{
	renderer_update_pad();
	renderer_update_sound();
}

void renderer_init()
{
	cur_time=0;
	
	renderer_reset();
}

void renderer_reset()
{
	pad_state=0;
	now_sensor_x=now_sensor_y=2047;
}

byte renderer_get_time(int type)
{
	unsigned long now=time(NULL)-cur_time;

	switch(type){
	case 8: // •b
		return (byte)(now%60);
	case 9: // •ª
		return (byte)((now/60)%60);
	case 10: // Žž
		return (byte)((now/(60*60))%24);
	case 11: // “ú(L)
		return (byte)((now/(24*60*60))&0xff);
	case 12: // “ú(H)
		return (byte)((now/(256*24*60*60))&1);
	}
	return 0;
}

void renderer_set_time(int type,byte dat)
{
	unsigned long now=time(NULL);
	unsigned long adj=now-cur_time;

	switch(type){
	case 8: // •b
		adj=(adj/60)*60+(dat%60);
		break;
	case 9: // •ª
		adj=(adj/(60*60))*60*60+(dat%60)*60+(adj%60);
		break;
	case 10: // Žž
		adj=(adj/(24*60*60))*24*60*60+(dat%24)*60*60+(adj%(60*60));
		break;
	case 11: // “ú(L)
		adj=(adj/(256*24*60*60))*256*24*60*60+(dat*24*60*60)+(adj%(24*60*60));
		break;
	case 12: // “ú(H)
		adj=(dat&1)*256*24*60*60+(adj%(256*24*60*60));
		break;
	}
	cur_time=now-adj;
}

void renderer_set_bibrate(bool bibrate)
{
}

word renderer_get_sensor(bool x_y)
{
	return (x_y?(now_sensor_x&0x0fff):(now_sensor_y&0x0fff));
}

int renderer_get_timer_state()
{
	return cur_time;
}

void renderer_set_timer_state(int timer)
{
	cur_time=timer;
}
