package AA::Anim;

my @timer_queue;
my $debug = 0;
my $now = 0;

our $timer = AA->new('T');
$timer->DefSet('T', 0);

sub now($) {
	return $timer->Get('T');
}

sub add_timer($$$) {
	my ($class, $after, $sub) = @_;
	my $t = $now + $after;
	push @timer_queue, [ $t, $sub ];
	print "@@@ Adding timer for $t\n" if $debug;
	@timer_queue = sort { $a->[0] <=> $b->[0] } @timer_queue;
}

sub add_final($$) {
	my ($class, $sub) = @_;
	push @timer_queue, [ 1000000, $sub ];
}

sub start($) {
	AA::Anim->add_final(sub { });
	$now = 0;
}

sub step($) {
	print "@@@ Tick tock: it's $now o'clock\n" if $debug;
	$timer->Set('T', $now);
	my $tm;
	if (!@timer_queue) {
		print "@@@ idle\n" if $debug;
		return 0;
	} elsif ($timer_queue[0]->[0] >= 1000000) {
		while ($tm = shift @timer_queue) {
			print "@@@ finalizer\n" if $debug;
			&{$tm->[1]};
		}
	} else {
		while (@timer_queue && $timer_queue[0]->[0] <= $now) {
			print "@@@ timer for ", $timer_queue[0]->[0], "\n" if $debug;
			$tm = shift @timer_queue;
			&{$tm->[1]};
		}
	}
	$now++;
	return 1;
}

sub ticker($$$$) {
	my ($class, $x0, $x1, $dt) = @_;
	my $t0 = $now;
	return sub {
		my $t = AA::Anim->now;
		if ($t - $t0 >= $dt) {
			return $x1;
		} else {
			return $x0 + ($x1 - $x0) * ($t - $t0)/$dt;
		}
	};
}

1;
