/*********************************************************************
*	CGameIntro
*	SOURCE FILE
*	Autor:	Michal Jirouš
*	Datum: 16.7.2008
*	Soubor: intro.cpp
*	Popis: Nacita seznam filmu a pomoci prehravace OggPlayer je postupne prehrava
*			v poradi, v jakem jsou zapsany v konfiguracnim souboru.
**********************************************************************/

#include "intro.h"
#include <fstream>
#include "SDL/SDL_opengl.h"
#include "sys_console.h"
#include "sys_config.h"

using namespace systemConsole;

using namespace std;

CGameIntro gameIntro;

CGameIntro::CGameIntro()
{
	m_bIsPlaying = false;
	m_bIntroFinnished = false;
}

//nacteni seznamu filmu
void CGameIntro::loadFiles( const char * filename )
{
	console << "Loading intro file list" << endline;

	m_bIntroFinnished = true;
	
	ifstream fin( filename, ios::in );
	if( !fin.is_open() )
	{
		console << "File not found: " << filename << "." << endline;
		return;
	}

	string name;
	while( !(fin >> name).eof() )
	{
		if( !name.empty() )
			m_fileQueue.push( "Movies/"+name );
	}

	if( m_fileQueue.empty() || !m_Player.loadFile( m_fileQueue.front().c_str() ) )
	{
		console << "No movie files has been loaded -> Quiting intro" << endline;
		return;
	}

	m_fileQueue.pop();
	m_bIsPlaying = true;
	m_bIntroFinnished = false;
}

//inicializace
void CGameIntro::init( SDL_Surface *surface, const char * filename )
{
	m_Player.init( surface );
	SDL_WM_SetCaption(systemconf::SYSTEM_WINDOW_TITLE.c_str(), NULL);// Titulek okna
	loadFiles( filename );
}


void CGameIntro::run()
{
	if( m_bIsPlaying )
	{
		m_Player.play();
		if( m_Player.isFinnished() )
		{
			m_bIsPlaying = false;
			next();
		}
	}
}

void CGameIntro::draw()
{
	m_Player.draw();
	glFlush();
	SDL_GL_SwapBuffers();// Prohodi predni a zadni buffer

}

//nacteni dalsiho filmu v proradi, pokud jeste takovy existuje
void CGameIntro::next()
{
	console << "-> Next movie." << endline;
	if( m_bIntroFinnished )
		return;

	if( m_fileQueue.empty() && ! m_bIntroFinnished)
	{
		m_Player.reset();
		m_bIsPlaying = true;
		m_bIntroFinnished = true;
		m_Player.destroy();
		return;
	}

	m_Player.reset();
	string fileName = m_fileQueue.front();
	m_fileQueue.pop();

	if( !m_Player.loadFile( fileName.c_str() ) )
	{
		m_bIntroFinnished = true;
		return;
	}

	m_bIsPlaying = true;
}

//ovladani
void CGameIntro::controller(SDL_Event &event)
{

	switch(event.type)
	{
		case SDL_KEYDOWN:
		case SDL_MOUSEBUTTONDOWN:
			next();
			break;
		default:
			break;
	}
}

void CGameIntro::main_loop()
{
	while( !m_bIntroFinnished )
	{
		SDL_Event event;
		while(SDL_PollEvent(&event))
		{
			gameIntro.controller( event );
		}
		run();
		draw();
	}
}

