package VDR::Plugin;

use strict;
use warnings;
use base qw[ Exporter VDR ];

use VDR::Object;
            
sub new {
	my $self = shift;
	my $ref = ref($self) || $self;

	return $ref->SUPER::new;
}

sub run
{
	my $this = shift;

	$this->send_msg('R');

	while (defined(my $line = readline($this->{_socket}))) {
		chomp $line;
		print STDERR "received: $line\n";
		$this->_handle_action($line);
	}
}

sub set_parameter
{
	my $this = shift;
	my $param = shift;
	my $value = shift;

	$this->send_msg('P', $param, $value);
}

sub _handle_action
{
	my $this = shift;
	my $action = shift;

	my @params = ();
	my $rest;
	($params[0], $rest) = split(/\s+/, $action, 2);
	while ($rest =~ /(\w+(?:=0x[a-f\d]+|)|'(?:(?<!\\)')*')\s*/g) {
		my $word = $1;
		if ($word =~ /^'/) {
			$word =~ s/^'|'$//g;
			$word =~ s/\\n/\n/g;
			$word =~ s/\\(.)/$1/g;
		}
		push @params, $word;
	}
	
	print STDERR "handleaction $action\n";

	if ($params[0] eq 'C' || $params[0] eq 'M') {
		my @response = ( lc(shift(@params)) );
		my $object = $this;
		my $result = undef;

		$object = VDR::Object::get(shift(@params)) if ($response[0] eq 'm');
		
		my $method = shift @params;

		if (defined($object->{_callbacks}{$method})) {
			$result = $object->{_callbacks}{$method}($object, @params);
		}
		elsif (exists(&{ref($object)."::$method"})) {
			no strict 'refs';
			$result = &{ref($object)."::$method"}($object, @params);
			use strict 'refs';
		}
		
		push @response, $result;
		$this->send_msg(@response);
	}
}

"this value intentionally left true";
