#!/usr/bin/perl -w

use strict;
use utf8;

use Gtk2 '-init';
use Glib qw(TRUE FALSE);

use SCX::GUI;
use SCX::Track;
use SCX::Reader;

my $gui = SCX::GUI->new({ img_height => 120 });
my $track = SCX::Track->new({ gui => $gui });

my $reader;
eval {
	$reader = SCX::Reader->new({
		portname   => '/dev/ttyUSB0',
		logfile    => 'log',
		track      => $track,
	});
};

if ($@) {
	print STDERR "Demo mode only: $@";
}

$track->car(0)->set_model('F1 Ferrari');
$track->car(1)->set_model('F1 McLaren');
$track->car(2)->set_model('F1 Williams');
$track->car(3)->set_model('Citroen Xsara');
$track->car(4)->set_model('Citroen C4');
$track->car(5)->set_model('Ford Focus');

$track->car(0)->set_driver('Ivi');
$track->car(1)->set_driver('Filípek');
$track->car(2)->set_driver('Táta');

if ($reader) {
	Glib::IO->add_watch(fileno($reader->fh), 'in', \&scx_read, $reader);
} else {
	# Just display some random values

	$gui->rounds('5/13');
	$gui->time('53.4');
	$gui->best_lap('12.3');

	my $now = time;
	$track->{race_running_since} = $now;
	$track->{race_running} = 1;

	$track->finish_line($now + 0.5, 1, 2);
	$track->finish_line($now + 0.7, 1, 1);
	$track->finish_line($now + 4.9, 1, 1);
	$track->finish_line($now + 5.3, 1, 2);
	$track->finish_line($now + 7.2, 1, 1);
	$track->finish_line($now + 8.1, 0, 2);
#	$track->car(0)->set_lap(13);
#	$track->car(1)->set_lap(11);
#	$track->car(2)->set_lap(10);
#	$track->car(3)->set_lap(undef);
#	$track->car(4)->set_lap(undef);
#	$track->car(5)->set_lap(undef);

	$track->car(0)->set_laptime(9.12322);
	$track->car(1)->set_laptime(15.313);
	$track->car(2)->set_laptime(5.989);

	$track->car(0)->set_fuel(6);
	$track->car(1)->set_fuel(2);
	$track->car(2)->set_fuel(8);

	$track->car(0)->set_throttle(0);
	$track->car(1)->set_throttle(8, 1);
	$track->car(2)->set_throttle(12);
}

$gui->show;

Gtk2->main();

exit 0;

sub quit {
	Gtk2->main_quit;
	return FALSE;
}

sub scx_read {
	my ($event, $fh, $reader) = @_;

	$reader->read();
	return TRUE;
}

