package PerlRPG::Game;
use strict;
require Exporter;
use SDL;
use SDL::Event;
use SDLx::App;
use SDLx::Sprite;
use SDLx::Sprite::Animated;
use PerlRPG::Console;
use PerlRPG::Assets;
use PerlRPG::Drawing;
use PerlRPG::Script;
use vars qw/$app @ISA @EXPORT @EXPORT_OK/;

@ISA = qw/Exporter/;
@EXPORT = qw/InitApp Run RunScript GetOption SetOption/;
@EXPORT_OK = @EXPORT;

$app = undef;
my %opt = (
	'App'		=> undef,
	'Running'	=> 1,
	'TargetFPS'	=> 5,
	'ResourceDir'	=> '.',
	'Status'	=> 'WaitForFrame',
);

sub GetOption { return (exists $opt{$_[0]} ? $opt{$_[0]} : undef); }
sub SetOption { $opt{$_[0]} = $_[1]; }


sub InitApp {
	my($width, $height)=@_;

	return undef if($app);

	LogData(INFO, "Creating SDL instance");
	$app = SDLx::App->new(
		width => $width,
		height => $height,
		);
	$opt{'App'}=$app;
	LogData(DEBUG, "SDL Instance created");
	return $app;
}

sub Run {
	my $tick = SDL::get_ticks();
	while($opt{'Running'}) {
		EventDispatcher();
		RunScriptTick();
		RenderScreen();

		my $ticktime = SDL::get_ticks() - $tick;
		my $delta = 1000/$opt{'TargetFPS'} - $ticktime;

		LogData(DEBUG, "TickTime = $ticktime, Delta = $delta");
		SDL::delay($delta) if($delta > 0);
		$tick = SDL::get_ticks();
	}
}

sub EventDispatcher {
	my $event = SDL::Event->new();
	SDL::Events::pump_events();
	while(SDL::Events::poll_event($event)) {
		if($event->type == SDL_KEYDOWN) {
			my $key = SDL::Events::get_key_name($event->key_sym);
			LogData(DEBUG, "KeyDown($key)");
		} elsif($event->type == SDL_KEYUP) {
			my $key = SDL::Events::get_key_name($event->key_sym);
			LogData(DEBUG, "KeyUp($key)");
		} elsif($event->type == SDL_QUIT) {
			$opt{'Running'} = 0;
		}
	}
}

sub RenderScreen {
	RenderSprites();
	$app->update();
}

sub RunScript {

}

1;
