package PerlRPG::Drawing;
use strict;
require Exporter;
use SDL;
use SDL::Event;
use SDLx::App;
use SDLx::Sprite;
use SDLx::Sprite::Animated;
use PerlRPG::Console;
use PerlRPG::Game;
use PerlRPG::Assets;
use Storable qw/dclone/;

use vars qw/@ISA @EXPORT @EXPORT_OK %VisibleSprites/;
@ISA = qw/Exporter/;
@EXPORT = qw/ ShowSprite HideSprite MoveSprite SetBackgroundColor RenderSprites /;
@EXPORT_OK = ();

# FIXME - This should be exported already?
*GetOption = \&PerlRPG::Game::GetOption;

sub ShowSprite {
	my($name, $file, $x, $y, $d, %opt)=@_;
	LogData(DEBUG, "Showing sprite $file as $name");

	my $t = GetAssetType($file);
	if($t ne 'Sprite' && $t ne 'ASprite') {
		LogData(WARN, "Unable to ShowSprite on non-sprite asset '$file'");
		return;
	}

	my $a = GetAsset($file);
	if($t eq 'ASprite') {
		# Unload the asset so that future versions of the same name will be fresh copies
		UnloadAsset($file);

		# Start animation
		$a->start();
	}

	foreach my $o (keys %opt) {
		if($o eq 'type') {
			$a->type($opt{$o});
		}
	}

	$VisibleSprites{$name}={
		'Depth'		=> $d,
		'X'		=> $x,
		'Y'		=> $y,
		'Sprite'	=> $a,
	};
	return 1;
}

sub HideSprite {
	my($name)=@_;
	delete $VisibleSprites{$name};
}

sub MoveSprite {
	my($name, $x, $y)=@_;
	return undef unless(exists $VisibleSprites{$name});
	$VisibleSprites{$name}{'X'} = $x;
	$VisibleSprites{$name}{'Y'} = $y;
}

sub SetBackgroundColor {
	my $color;
	if(!@_) {
		$color = [0, 0, 0, 255];
	} elsif(ref $_[0]) {
		$color = $_[0];
	} else {
		$color = [@_];
	}

	# Force alpha channel?
	$color->[3]=255;

	my $app = GetOption('App');
	my $surface = SDLx::Surface->new(width => $app->width(), height => $app->height());
	$surface->draw_rect([0, 0, $surface->width(), $surface->height()], $color);
	my $sprite = SDLx::Sprite->new( surface => $surface );
	$VisibleSprites{'Background'}={
		'Depth'		=> -1,
		'X'		=> 0,
		'Y'		=> 0,
		'Sprite'	=> $sprite
	};
}

sub RenderSprites {
	my $app = GetOption('App');
	my @names = sort { $VisibleSprites{$a}{'Depth'} <=> $VisibleSprites{$b}{'Depth'} } (keys %VisibleSprites);
	foreach my $name (@names) {
		my $x = $VisibleSprites{$name}{'X'};
		my $y = $VisibleSprites{$name}{'Y'};
		$VisibleSprites{$name}{'Sprite'}->draw_xy($app, $x, $y);
	}
}

1;
