package Quancom::Result;
#    Quancom::Result - Result class for Quancom module
#    Copyright (C) 2008  Heiko Schlittermann
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#    Heiko Schlittermann <hs@schlittermann.de>

use strict;
use warnings;

sub new {
    my $class = ref $_[0] ? ref shift : shift;
    my $self = bless {} => $class;
    my $r = shift;
    $r =~ s/\s*$//;    # should match any \r or \n too

    # decode the status
    if (($self->{error_code}) = $r =~ /^E(.)/) {
        $self->{ok} = 0;
    }
    elsif (my ($jobid, $data, $csum) = $r =~ /^[DO](..)(.*)(..)$/) {
        $self->{ok} = 1;
        $self->{data} = defined $data ? $data : "";
    }
    else {
        die "unknown response $r";
    }

    return $self;
}

sub ok {
    my $self = shift;
    return $self->{ok};
}

sub data {
    my $self = shift;
    return undef if not $self->{ok};
    return $self->{data};
}

sub error {
    my $self = shift;
    return $self->{ok} ? undef : $self->{error_code};
}

sub error_message {
    my $self = shift;

    return undef if !@_ and $self->{ok};

    return ("checksum error", "character error", "invalid command",
        "invalid width")[ @_ ? $_[0] : $self->{error_code} ];
}

1;

__END__

=head1 NAME

Quancom::Result - perl module to access the usb opto quancom device result

=head1 SYNOPSIS

    use Quancom;

    my $quancom = new Quancom 172.16.0.22;
    my $result = $q->cmd("xxxxxx");

    if ($result->error) { die $result->error_message }
    else { print $result->data, "\n" }

=head1 METHODS

=over

=item constructor B<new> ( )

Probably you'll never use this.

=item B<data> ( )

Returns the last result. This is valid only if the last status is ok,
otherwise you'll get "undef".

=item B<error> ( )

Returns the error code - if any - or 'undef' if there was no error.

=item B<error_message> ( [I<error code>] )

Returns a message describing the last error. Of if you pass an error
code it will the return the associated message.

=item B<ok> ( )

Use this method to query the last operations status.

=back

=head1 SEE ALSO

L<Quancom>

=head1 AUTHOR

    Maik Schueller
    Heiko Schlittermann

=cut
