#include <stdlib.h>
#include "SDL/SDL.h"
#include "display_scene.h"
#include "../common/structs.h"
#include "../common/debug.h"
#include "../common/buffer.h"
#include "../misc/save_frame.h"
//#include "../../shader/noise.h"
#include "front_init.h"
#include "handle_input.h"
#include "console.h"
#include <time.h>
#include <strings.h>
#include "globals.h"

#include "../render/render_scene.h"

extern clock_t current_time;
extern char frame_break_text[INPUT_COMMAND_LENGTH];

int display_scene()
{

	printd(CRAZY, "Displaying scene\n");
	while( frontend->running )
	{
		handle_input();
		current_time = clock();

		render_scene(frontend->renderer);
		copy_buffer(frontend->screen);
		SDL_UpdateRect(frontend->screen, 0,0,0,0);
		
		printd(DEBUG, "%i\n", frontend->running);
	}

	return 1;
}



int copy_buffer(SDL_Surface* screen)
{
	unsigned char* old_buffer;
	Uint32* new_buffer;
	Uint8 R, G, B;
	Uint32 sdl_color;
	int x,y;
	
	static struct timespec sleeptime;
	
	sleeptime.tv_sec = 0;
	sleeptime.tv_nsec = 100000000;
	
	if(main_scene->models[1] == NULL)
		nanosleep(&sleeptime, NULL);

	printd(CRAZY, "Copying buffer\n");
	old_buffer = main_scene->frame_buffer;
	for(y=0; y < main_scene->height; y++)
	{
		for(x=0; x < main_scene->width; x++)
		{
			printd(INSANE, "Copying color @ %i, %i\n", x, y);

			R = *old_buffer;
			old_buffer++;
			G = *old_buffer;
			old_buffer++;
			B = *old_buffer;
			printd(INSANE, "%i\n", B);
			old_buffer++;

			printd(INSANE, "Making color\n");
			sdl_color = SDL_MapRGB(screen->format, R, G, B);

			printd(INSANE, "Making pointer\n");
			new_buffer = (Uint32*)screen->pixels + y * screen->pitch/4 + x;

			printd(INSANE, "Setting color\n");
			*new_buffer = sdl_color;
			//*new_buffer = 0xffff;
			printd(INSANE, "%x,%x,%x -- %x, %x\n", R,G,B,sdl_color, *new_buffer);
		}
	}
	
	if(frontend->console_on)
	{
		draw_console(screen);
		print_to_bottom(frame_break_text);
	}

	draw_buttons(screen);
	printd(CRAZY, "Done copying buffer\n");

	return 1;
}

