package WvCamera;

use strict;
use LWP::Simple;

sub new {
    my($class,$server,$port)=@_;
    my $self={
        "server" => $server,
        "port"   => $port,
        "id"     => "",
        "info"   => {}
    };
    return bless $self,$class;
}

sub _mr {
    my($this,$request)=@_;
    my $url="http://$this->{server}:$this->{port}/-wvhttp-01/$request";
    my $r=get($url);
    chomp $r;
    return $r;
}

sub connect {
    my($this)=@_;
    if (my $r=$this->_mr("OpenCameraServer?client_version=LiveApplet_3109&image_size=320x240&VC_HOST=localhost&CC_HOST=localhost")) {
        my $connid=(split /=/,$r)[1];
        $this->{id}=$connid;
        return 1;
    }
    else {
        return 0;
    }
} 

sub disconnect {
    my($this)=@_;
    return ($this->_mr("CloseCameraServer?connection_id=$this->{id}") eq "OK.") ?
        1 : 0;
}

sub get_control {
    my($this)=@_;
    return ($this->_mr("GetCameraControl?connection_id=$this->{id}") eq "OK.") ?
        1 : 0;
}

sub populate_info {
    my($this)=@_;
    my $r=$this->_mr("GetCameraInfo?connection_id=$this->{id}");
    for my $line (split /\n/,$r) {
        my($key,$value)=split /=/,$line;
        $this->{info}->{$key}=$value;
        #print "Got $key: '$value'\n";
    }
    return $r ? 1 : 0;
}

sub have_control {
    my($this)=@_;
    $this->populate_info();
    my $t=$this->{info}->{tilt_current_value};
    return $this->tilt($t/100);
}

sub capture {
    my($this,$file)=@_;
    $file ||= "capture.jpg";
    return (qx(wget -q -O $file http://$this->{server}:$this->{port}/-wvhttp-01-/GetStillImage)) ? 0 : 1;
}

sub move {
    my($this,$operation,$position)=@_;
    $position *= 100;
    #print "* Operation: $operation to position $position\n";
    my $r=$this->_mr("OperateCamera?$operation=$position&connection_id=$this->{id}");
    #if ($r ne "OK.") { print STDERR "$r\n"; }
    return ($r eq "OK.") ? 1 : 0;
}

sub tilt {
    my($this,$position)=@_;
    return $this->move("tilt",$position);
}

sub pan {
    my($this,$position)=@_;
    return $this->move("pan",$position);
}

sub zoom {
    my($this,$position)=@_;
    return $this->move("zoom",$position);
}

sub goto {
    my($this,$pan,$tilt,$zoom)=@_;
    return ($this->tilt($tilt) && $this->pan($pan) && $this->zoom($zoom));
}

1;
