#!/usr/bin/perl

use strict;
use warnings;
use lib "/opt/pos/lib";
use FindBin qw( $Bin );
use Data::Dumper;
use Spreadsheet::ParseExcel::Simple;
use JSON::XS qw( encode_json decode_json );
use LWP::UserAgent;
use File::Find qw( find );
use Compress::Zlib qw( compress uncompress );
use HTTP::Request::Common qw( POST PUT GET );
use Encode qw( encode_utf8 decode_utf8 );
use App::POS::Check;
use App::POS::Machine::Server;

_cleanup();

my $API = 'http://apis.opalaconsult.com/db_storage';

my $hardlock = `/opt/pos/common/bin/machine_id`;

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

my %info = ();
my $recs = $db->select(qq{
  SELECT p.*, g2.name as group, g.name AS dept
  FROM products p
  LEFT JOIN product_groups pg ON (p.id = pg.product_id)
  LEFT JOIN groups g ON (g.id = pg.group_id)
  LEFT JOIN groups g2 ON (g.parent = g2.id)
  WHERE p.deleted = 0
});

for (@$recs) {
  # next unless $_->{group} && $_->{dept};
  delete $_->{vat_isention};

  $_->{name} ||= "";
  $_->{button_text} ||= "";
  $_->{barcode} ||= "";

  if ($_->{name}) {
    $_->{name} =~ s/"//g;
    $_->{name} =~ s/\\//g;
  }

  if ($_->{button_text}) {
    $_->{button_text} =~ s/"//g;
    $_->{button_text} =~ s/\\//g;
  }

  if ($_->{barcode}) {
    $_->{barcode} =~ s/"//g;
    $_->{barcode} =~ s/\\//g;
  }

  $info{$_->{id}} = $_;
}

my $ret = _post_json_compressed("$API/upload_records", $hardlock, \%info);
$ret ||= {};

if (exists $ret->{error}) {
  die "Got error from API... $ret->{error}\n";
}
elsif (exists $ret->{success}) {
  print STDERR "Success...\n";
}

#
# functions
#

sub _post_json_compressed {
  my $url = shift;
  my $token = shift;
  my $ref = shift;

  my $comm = LWP::UserAgent->new();
  my %params = ();

  my $file = "$Bin/to_post.$$.".int(rand(100000)).".data";

  my $json = decode_utf8(encode_json($ref));
  #print STDERR "$json\n";

  open(F, "> $file");
  binmode(F);
  print F compress(encode_utf8($json));
  close(F);

  my $method = 'http';

  my $req = POST(
    $url,
    Content_Type => 'multipart/form-data',
    Content => [ token => $token, file_upload => [ $file ], %params ],
  );

  my $r = $comm->request($req);

  unlink $file;

  if ($r->code() != 200) {
    print STDERR "Error posting... " . $r->content()."\n";
    return undef;
  }
  else {
    return decode_json($r->content());
  }
}

sub _post_json {
  my $url = shift;
  my $ref = shift;
  my $method = shift;
  return unless defined $url;

  $method = 'POST' unless defined $method;

  my $ua = LWP::UserAgent->new();
  $ua->timeout(5);

  my $req = HTTP::Request->new($method => $url);
  $req->header('content-type' => 'application/json');

  $req->content(encode_json($ref));

  my $r = $ua->request($req);

  if ($r->code() != 200) {
    print STDERR "Error posting... " . $r->content()."\n";
    return undef;
  }
  else {
    return decode_json($r->content());
  }
}

# cleanup old post files that might be in the folder
sub _cleanup {
  find(sub {
    return if -d $File::Find::name;
    return unless /^to_post\./;
    unlink($File::Find::name);
  }, ( $Bin ));
}

