#!/usr/bin/perl

use strict;
use warnings;
use lib qw( /opt/pos/lib );
use Data::Dumper;
use File::Copy qw ( move );
use App::POS::Config;
use App::POS::Machine::Server;
use App::POS::Machine::Station;

my $cfg = App::POS::Config->new( file => "/opt/pos/etc/config.ini" );
my $info = $cfg->load_fixed();
my $machine;

if (exists $info->{STATION_NUMBER} && $info->{STATION_NUMBER} > 0) {
  $machine = App::POS::Machine::Station->new( config => $cfg );
}
else {
  $machine = App::POS::Machine::Server->new( config => $cfg );
}

my $print_file = "";

$info->{Hardware}->{Printers}->{Device} ||= [];

for (my $i=0; $i<scalar @{$info->{Hardware}->{Printers}->{Device}}; $i++) {
  my $p = $info->{Hardware}->{Printers}->{Device}->[$i];
  $p->{Main} ||= 0;

  if ($p->{Main}) {
    $print_file = "/opt/pos/common/tmp/print#".$info->{STATION_NUMBER}."#$i#0#".time.$$.".txt";
  }
}

  die "Error finding print file..." unless $print_file;


  my $price_num = $_; 
  my $code_field = $_;
  my $sort_field = $_;
  my $pp = &products_prices(
    machine => $machine,
    price_number => $price_num,
    code_field => $code_field,
    sort_field => $sort_field,
  );

  my $file = "/tmp/out.txt";

  open(F, "> $file") or die "Can't write to $file: $!\n";

  print F "------.--------------------------.------\n";
  print F sprintf("%5s", 'Codigo')." ".sprintf("%-26s", "Nome")." ".sprintf("%6s", "Preco$price_num")."\n";
  print F "------.--------------------------.------\n";

  foreach my $p (@$pp) {
    $p->{name} = substr($p->{name}, 0, 25);
    $p->{name} =~ s/\s/_/g;
    $p->{name} =~ s/\W//g;

    my $spaces = 26 - length($p->{name});
    $p->{name} .= "_" x $spaces;

    my $price = sprintf("%.2f", $p->{"sell_price".$price_num});
    $spaces = 6 - length($price);
    $price = ("_" x $spaces) . $price;

    print F sprintf("%6s", $p->{$code_field})." ".sprintf("%-26s", $p->{name})."_".sprintf("%6s", $price)."\n";
  }

  print F "----------------------------------------\n";

  close(F);

  &move($file, $print_file);
#
# Functions
#

sub products_prices {
  my %a = (
    machine => undef,
    price_number => 1,
    code_field => 'id',
    sort_field => 'name',
    @_,
  );

  die "Missing 'machine'..." unless defined $a{machine};
print "####".$a{code_field};
  my $c = $a{code_field};
  my $p = $a{price_number};
  my $sf = $a{sort_field};

  my $db = $machine->database();

  my $recs = $db->select(qq{
    SELECT $c, sell_price$p, name
    FROM products
    WHERE deleted = 0 AND $c <> '0' AND sell_price$p <> 0 AND name <> '--' AND name <> ''
    ORDER BY $sf
  });

  return $recs;
}

sub ui_question {
  my %a = (
    title => 'Window title',
    options => [],
    timeout => 10,
    @_,
  );

  my $buttons_str = "";

  foreach my $o (@{$a{options}}) {
    $buttons_str .= "   $o   ,";
  }

  $buttons_str =~ s/,$//;

  system("xmessage -timeout $a{timeout} -center -buttons \"$buttons_str\" \"$a{title}\"");

  my $ret = $? >> 8;
  return ($ret - 100) - 1;
}

