# Controller.pm --- regulates the traffic lights

package Controller;

use Timer;
use TrafficLight;

# Create a Controller class instance (instantiation)
sub new {
	my $class = ref($_[0]) || $_[0];
	my $this = {};
	bless $this, $class;
	$this->{'timer'} = new Timer($_[1]);
	$this->{'timer'}->addListener(\&Controller::changeState, $this);
	$this->{'tlight'} = undef;
	return $this;
}

# Specifies which traffic light to regulate
sub setTrafficLight {
	my $this = $_[0];
	$this->{'tlight'} = $_[1];
}

# Invoked automatically when a traffic light need to change state
sub changeState {
	my $this = shift;
	my $currentstate = $this->{'tlight'}->state();
	$this->{'tlight'}->state(1 - $currentstate);
}

# Go into an infinite loop
sub start {
	my $this = $_[0];
	$this->changeState();	# This has to be called for first time
	# Pick the first one and go
	while (1) {
		# Reset timer
		$this->{'timer'}->start;
	}
}

1;
