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

use warnings;
use strict;
use Time::HiRes qw( sleep );
use App::POS::Hardware::Scales;
use Data::Dumper;
use File::Slurp qw( write_file );

use base qw( App::POS::Hardware::Scales );

sub setup_port {
  my $s = shift;

  my $PortObj = $s->serial_obj();
  $PortObj->baudrate(38400);
  $PortObj->parity("none");
  $PortObj->databits(8);
  $PortObj->stopbits(1);
  $PortObj->handshake("none");
}

sub start {
  my $s = shift;

  my $cfg = $s->info();
  my $machine = $s->machine();

  my $PortObj = $s->serial_obj();

  my $sleep = 0.2;
  my $clean_after = 0;

  my $stations_to_notify = "";

  if (exists $cfg->{Aux1} && $cfg->{Aux1} ne '') {
    $stations_to_notify = $cfg->{Aux1};
  }

  my $message = $cfg->{Aux2} || "";

  my @to_ignore = (
    '2f9',
  );

  $stations_to_notify =~ s/\s//g;
  my @stations = split /,/, $stations_to_notify;

  my $dir_server_tmp = $machine->server_dir_tmp();

  if ($stations_to_notify eq '' || ! $message) {
    $s->debug("Missing Aux1 or Aux2 parameter with stations_to_notify and message");
  }

  while (1) {
    my( $count_in, $string_in ) = $PortObj->read(50);

    # means service call was used
    if ($count_in) {
      $string_in =~ s/\W//g;

      $s->debug("chars read: $count_in, string_read: #$string_in# - $dir_server_tmp");

      if (length($string_in) >= 8) {

        my $to_ignore = 0;

        foreach my $i (@to_ignore) {
          if ($string_in =~ /$i/) {
            $to_ignore = 1;
            last;
          }
        }

        if (! $to_ignore) {
          foreach my $st (@stations) {
            my $call_file = "$dir_server_tmp/service_call_show#".$st.".txt";
            my @other_stations = grep { $_ ne $st } @stations;
            my $others_str = join(",", @other_stations);
            $others_str ||= "";
            write_file($call_file, $message."\n".$others_str) if $message;
          }
        }

      }
    }

    sleep $sleep;
  }
}

1;


