package App::POS::Hardware::Scales;

use strict;
use warnings;
use Device::SerialPort;
use App::Class;

use base qw( App::Class );

sub init {
  my $s = shift;

  my %a = (
    machine    => undef,
    device     => undef,
    info       => undef,
    serial_obj => undef,
    debug_readings => 0,
    @_,
  );

  die "Missing 'machine' parameter..." unless defined $a{machine};
  die "Missing 'device' parameter..." unless defined $a{device};
  die "Missing 'info' parameter..." unless defined $a{info};

  $s->{debug_readings} = $a{debug_readings};

  my $info = $a{info};

  my $p = Device::SerialPort->new( $s->device() )
    or die "Device::SerialPort error: $!";

  $info->{Baudrate} = "" if ! exists $info->{Baudrate};
  $info->{Parity} = "" if ! exists $info->{Parity};
  $info->{Databits} = "" if ! exists $info->{Databits};
  $info->{Stopbits} = "" if ! exists $info->{Stopbits};
  $info->{Handshake} = "" if ! exists $info->{Handshake};

  $s->serial_obj($p);
  $s->setup_port();

  $p->baudrate($info->{Baudrate}) if $info->{Baudrate} ne '';
  $p->parity($info->{Parity}) if $info->{Parity} ne '';
  $p->databits($info->{Databits}) if $info->{Databits} ne '';
  $p->stopbits($info->{Stopbits}) if $info->{Stopbits} ne '';
  $p->handshake($info->{Handshake}) if $info->{Handshake} ne '';
}

sub device {
  my $s = shift;
  @_ ? $s->{device} = shift : $s->{device};
}

sub info {
  my $s = shift;
  @_ ? $s->{info} = shift : $s->{info};
}

sub machine {
  my $s = shift;
  @_ ? $s->{machine} = shift : $s->{machine};
}

sub serial_obj {
  my $s = shift;
  @_ ? $s->{serial_obj} = shift : $s->{serial_obj};
}

sub setup_port {
  die "'setup_port' method needs to be overrided...\n";
}

sub debug_readings {
  my $s = shift;
  return $s->{debug_readings};
}

sub debug {
  my $s = shift;
  my $m = shift;

  if ($s->debug_readings()) {
    print STDERR "$m\n";
  }
}

1;

