#!/usr/bin/perl

use strict;
use warnings;
use lib "/opt/pos/lib";
use Data::Dumper;
use JSON::XS qw( encode_json decode_json );
use HTTP::Request::Common qw( POST PUT GET );
use LWP::UserAgent;
use Encode qw( encode decode );
use App::POS::Utils qw( post );
use App::POS::Config;
use App::POS::Machine::Station;
use App::POS::Machine::Server;
use App::POS::Utils qw( log );

my $PRODUCT_CODE = shift || "";
die "Usage: $0 <product_code>\n" unless $PRODUCT_CODE;

use constant VERSION => '1.0.0';

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 $log_file = $machine->server_dir_data() . '/airmenu.log';

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

my $prod_info = $db->select(
  "SELECT sell_price1, online, soldout FROM products WHERE id = ? AND deleted = 0",
  $PRODUCT_CODE,
);

die "Can't find product with id $PRODUCT_CODE\n" unless scalar @$prod_info;

my $price = $prod_info->[0]->{sell_price1};
my $online = $prod_info->[0]->{soldout} ? JSON::XS::false : JSON::XS::true;

$cfg = $machine->server_config();
$info = $cfg->load_fixed();

$info->{AIRMENU_KEY} ||= '';
$info->{AIRMENU_LOGIN} ||= '';
$info->{AIRMENU_PASSWD} ||= '';
$info->{AIRMENU_ENTERPRISE_ID} ||= 0;
$info->{AIRMENU_AREA} ||= 0;

die "Missing AIRMENU_KEY or AIRMENU_LOGIN or AIRMENU_PASSWD or AIRMENU_ENTERPRISE_ID...\n"
  unless $info->{AIRMENU_KEY} && $info->{AIRMENU_LOGIN} && $info->{AIRMENU_PASSWD} &&
  $info->{AIRMENU_ENTERPRISE_ID};

my $airmenu_key = $info->{AIRMENU_KEY};
my $airmenu_user = $info->{AIRMENU_LOGIN};
my $airmenu_pass = $info->{AIRMENU_PASSWD};
my $airmenu_enterprise = $info->{AIRMENU_ENTERPRISE_ID};

my $data = {};

# ###################################################################
# AirMenu - Authenticate
# ###################################################################

$data = {
  ACTION   => 'Authenticate',
  VERSION  => VERSION,
  KEY      => $airmenu_key,
  DATA     => encode_json({
    username => $airmenu_user,
    password => $airmenu_pass,
  }),
};

my $ref = _post_form('http://www.airmenu.com/AirMenuAPI', $data);
$ref->{status} ||= "";
$ref->{sessionId} ||= "";

log($log_file, "airmenu_product_update.pl,Authenticate,plu:$PRODUCT_CODE,status:$ref->{status},sessionId:$ref->{sessionId}", 1);

die "Can't authenticate...\n" unless $ref->{status} eq 'SUCCESS';

$data = {
  ACTION   => 'UpdateMenuNodes',
  VERSION  => VERSION,
  KEY      => $airmenu_key,
  DATA     => encode_json({
    enterpriseId => $airmenu_enterprise,
    sessionId => $ref->{sessionId},
    menuNodes => [
      {
        available => $online,
        plu => $PRODUCT_CODE,
        menuRelation => 'item',
        price => $price,
      }
    ]
  }),
};

print STDERR Dumper($data);

$ref = _post_form('http://www.airmenu.com/AirMenuAPI', $data);
$ref->{status} ||= "";

log($log_file, "airmenu_product_update.pl,UpdateMenuNodes,plu:$PRODUCT_CODE,status:$ref->{status},price:$price,available:$online", 1);

print Dumper($ref);

#
# functions
#

sub _post_form {
  my $url = shift;
  my $data = shift || {};
  my $timeout = shift || 10;
  return unless defined $url;

  $data ||= {};

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

  my $r = $ua->request(POST $url, [
    %$data
  ]);

  return undef if $r->code != 200;

  my $cnt = $r->content();
  #print $cnt."\n";
  $cnt =~ s/RESULT=//;
  return decode_json(encode("utf8", $cnt));
}

