package Signal;

sub new {
    my $type = shift;
    my %params = @_;
    my $self = {};
    $self->{'State'}  = $params{'State'};
    $self->{'States'}  = ['green','yellow','red'];
    bless $self;
}

sub next {
    my ($self) = shift;
    my $state = $self->{'State'};
    if($state eq 'red') {
	$self->{'State'} = 'green';
    } elsif($state eq 'green') {
	$self->{'State'} = 'yellow';
    } else {
	$self->{'State'} = 'red';   # Red for all other cases 
    }
    # return $self->{'State'};
}

sub print {
    my ($self) = shift;
    my $state = $self->{'State'};
    print $state;
}


use Tk;

package MainWindow;

sub Signal {
    my ($self) = shift;
    return SignalView->new(-main=>$self);
}

package SignalView;
sub new {
    my $type = shift;
    my %params = @_;
    my $self = {};
    my $signal = Signal->new(%params);
    my $main = $params{-main};
    my $canvas;
    my $states = $signal->{'States'};
    my %views = ();

    $canvas = $main->Canvas(-width=>50,-height=>150);

    $x = 5; $y = 5;
    $r = 40;
    for $state ( @$states ) {
	$views{$state} = 
	    $canvas->create('oval', $x, $y, $x+$r, $y+$r, 
		-width => 1, -outline => 'black', -fill => 'black');
	$y += 50;
    }
    $canvas->pack();
    $self->{'MainWindow'}  = $main;
    $self->{'Canvas'}  = $canvas;
    $self->{'Views'}  = \%views;
    $self->{'Signal'}  = $signal;
    bless $self;
}

sub next {
    my ($self) = shift;
    my $state = $self->{'Signal'}->{'State'};
    my $view = $self->{'Views'}->{$state};
    my $canvas = $self->{'Canvas'};

    $canvas->itemconfigure($view,-fill=>'black');
    $state = $self->{'Signal'}->next();
    $view = $self->{'Views'}->{$state};
    $canvas->itemconfigure($view,-fill=>$state);
}

sub update {
    my ($self) = shift;
    $self->{'MainWindow'}->update();
}

package Main;

$main=MainWindow->new();
$signal = $main->Signal();

$signal->update();
while($i++<100) {
    $signal->next();
    $signal->{'Signal'}->print(); print "\n";
    $main->update();
    sleep(1);
}

# end
