#include <string>
#include <iostream>
#include "video_int.h"
#include "video.h"
#include "effects.h"
#include "countdown.h"
#include "me_time.h"
#include "snow.h"
#include "imageloader.h"
#include "music.h"
#include "text.h"

void scene_3d_init ( float w, float h, float fov );
void scene_3d ( void );
float scene_3d_animate ( void );
bool intro ( Video_Interface *vid, std::string vid_name );

bool run_demo ( std::string video_name )
{
	init_music();
	Video_Interface *vid = video_get_interface ( "Video" );
	std::cerr << __FUNCTION__ << std::endl;
	vid->_enable_keyboard_event(true);
	Music intro_m;
	intro_m.load("res/music/intro.ogg");
	intro_m.play(0);
	if ( !intro ( vid, video_name ) ) return false;
	intro_m.stop();

	Music main_m;
	main_m.load("res/music/main.ogg");
	if(!imageloader_loadimage ( "png", video_name, "res/images/fg.png", "fg", "main_fg" ))
	{
		std::cerr<<"Cant load image \"res/images/fg.png\":"<<imageloader_error()<<std::endl;
		return false;
	}
	if(!vid->_create_sprite("main_fg", "fg", "main_fg", "fg", false))
	{
		std::cerr<<"Cant create sprite:"<<vid->_get_error()<<std::endl;
		return false;
	}
	Video_Sprite *fg;
	if(!(fg=vid->_get_sprite("main_fg", "fg")))
	{
		std::cerr<<"Cant get sprite:"<<vid->_get_error()<<std::endl;
		return 1;
	}
	fg->_set_coord(-1, -1);


	std::vector<effects*> effects_2d;
	std::vector<effects*>::iterator effects_2d_it;

	effects *ef;
	ef = new countdown();
	ef->prepare ( video_name, vid );
	effects_2d.push_back ( ef );
	
	ef=new snow(24000);
	ef->prepare(video_name, vid);
	effects_2d.push_back(ef);

	ef=new text();
	ef->prepare(video_name, vid);
	effects_2d.push_back(ef);
	
	
	
	int frames_total = 0, frame_was = 0;
	Time timer;
	scene_3d_init ( vid->_get_width(), vid->_get_height(), 30.0 );

	main_m.play();
	for ( ;; )
	{
		float dy_angle = scene_3d_animate();
		
		scene_3d();
/*		if(!vid->_add_sprite("main_fg", "fg"))
		{
			std::cerr<<"Error putting surface:"<<vid->_get_error()<<std::endl;
			return 1;
		}*/
		for ( effects_2d_it = effects_2d.begin();effects_2d_it != effects_2d.end();++effects_2d_it )
		{
			( *effects_2d_it )->run ( frames_total, vid, dy_angle );
		}
		vid->_draw();
		
		++frames_total;
		Event type = vid->_get_event();
		if ( type._get_type() != NO_EVENT && type._get_type( ) != MOUSE_MOVE )
		{
			main_m.stop();
			break;
		}
		if ( frames_total - frame_was >= 500 )
		{
			double dt = timer.get_elapsed_time();
			std::cerr << frames_total - frame_was << " frames in " << dt << " seconds. FPS:" << float ( frames_total - frame_was ) / dt << std::endl;
			frame_was = frames_total;
		}

	}
	return true;
}

