#!/usr/bin/perl -w

use strict;
use utf8;

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

use SCX::Reader;

my @controllers = (0, 0, 0, 0, 0, 0);

my $builder = Gtk2::Builder->new;
$builder->add_from_file('slotcarman.glade');

my $window = $builder->get_object('slotcarman');

$builder->connect_signals(undef);
$window->show();

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

my $reader = SCX::Reader->new({
	portname   => '/dev/ttyUSB0',
	logfile    => 'log',
	callback   => \&do_packet,
});

sub scx_read {
	my $event = shift;

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

Glib::IO->add_watch(fileno($reader->fh), 'in', \&scx_read, 1);

Gtk2->main();

sub do_packet {
	my (@data) = @_;

	if ($data[0] == 0xff) { # controller status
		for my $controller (1..6) {
			my $byte = $data[$controller];
			next if defined $controllers[$controller-1]
				&& $controllers[$controller-1] == $byte;
			$controllers[$controller-1] = $byte;

			my $progressbar = $builder->get_object(
				'progressbar_controller'.$controller);
			if ($byte == 0xaa) {
				$progressbar->set_text('inactive');
				$progressbar->set_fraction(0);
				next;
			}
			my $light = !($byte & 0x20);
			my $backbutton = !($byte & 0x10);
			my $speed = $byte & 0x0f;

			my $text = ($backbutton ? '+' : '') . $speed;
			$progressbar->set_text($text);
			$progressbar->set_fraction($speed / 12);
		}
	} elsif ($data[0] == 0xd6) { # fuel status
		my @fuel = (0,
			$data[1] >> 4, $data[1] & 0x0f,
			$data[2] >> 4, $data[2] & 0x0f,
			$data[3] >> 4, $data[3] & 0x0f,
		);
		for my $car (1..6) {
			next if defined $controllers[$car-1]
				&&$controllers[$car-1] == $fuel[$car];
			
			my $progressbar = $builder->get_object(
				'progressbar_fuel'.$car);
			$progressbar->set_fraction($fuel[$car]/8);
		}
	} else {
		print "Unknown packet",
			(map { sprintf(" %02x", $_) } @data), "\n";
	}
}
			
__END__
use Gtk2 '-init';

my $window = Gtk2::Window->new('toplevel');
$window->signal_connect(delete_event => sub { Gtk2->main_quit; return FALSE });
$window->set_title("Slot Cars Manager");

$window->set_border_width(10);

my $button = Gtk2::Button->new("Button 1");
$button->signal_connect(clicked => \&callback, 'button 1');

my $box1 = Gtk2::HBox->new(FALSE, 0);
$window->add($box1);
$box1->pack_start($button, TRUE, TRUE, 0);

$button->show;
$button = Gtk2::Button->new("Button 2");
$button->signal_connect(clicked => \&callback, 'button 2');
$box1->pack_start($button, TRUE, TRUE, 0);

$button->show;
$box1->show;
$window->show;

Gtk2->main();


sub callback
{
	my ($button, $data) = @_;
	
	print "Hello again - $data was pressed\n";
}

