#!/usr/bin/perl

use strict;
use warnings;
use FindBin qw( $Bin );
use lib "$Bin/../../lib";
use Data::Dumper;
use IO::Socket;
use App::POS::Config;
use App::POS::Machine::Server;

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

my $PRODUCTS_SUGESTION_DONT_LEARN = $info->{PRODUCTS_SUGESTION_DONT_LEARN} || "0";
exit if $PRODUCTS_SUGESTION_DONT_LEARN;

#my $file = "/opt/pos/server/data/database/products_suggestions.db";

if (exists $info->{STATION_NUMBER} && $info->{STATION_NUMBER} == 0) {
  #if (! -e $file) {
  #  print STDERR "No suggestions file, will exit...\n";
  #  exit;
  #}

  my $server = App::POS::Machine::Server->new( config => $cfg );
  my $db = $server->database();

  my $products_suggest = App::POS::Counters->new(
    db => $db,
    name => 'products_suggest',
  );

  my %sug = $products_suggest->all_key_values();
  #print STDERR Dumper(\%sug);

  my $info = {};

  foreach my $k (keys %sug) {
    my @tok = split /#/, $k;

    # global read
    if (scalar @tok == 2) {
      $info->{global}->{$tok[0]}->{$tok[1]} = $sug{$k};
    }
    # station or area read
    else {
      my( $t, $v ) = $tok[2] =~ /^(\w+)=(\d+)$/;
      my $key = undef;

      if (defined $t) {
        # area
        if ($t eq 'a') {
          $key = 'by_area';
        }
        # station
        elsif ($t eq 's') {
          $key = 'by_station';
        }
      }

      if (defined $key) {
        $info->{$key}->{$v}->{$tok[0]}->{$tok[1]} = $sug{$k};
      }
    }
  }

  $info->{global} ||= {};
  my $wrote = 0;

  open(F, "> /opt/pos/server/data/products_relevance.txt");

  if (scalar keys %{ $info->{global} }) {
    print F "[global]\n";

    foreach my $id (keys %{ $info->{global} }) {
      print F "$id=";
      foreach my $sid (reverse sort { $info->{global}->{$id}->{$a} <=> $info->{global}->{$id}->{$b} } keys %{ $info->{global}->{$id} }) {
        #print STDERR "###### $id -> $sid -> ".$info->{global}->{$id}->{$sid}."\n";
        print F $sid.",";
        $wrote = 1;
      }
      print F "\n";
    }
  }

  close(F);

  if ($wrote) {
    my $sock = IO::Socket::INET->new(
      PeerAddr => '127.0.0.1',
      PeerPort => '8088',
      Proto => 'tcp',
      Timeout => 5,
    );

    if (defined $sock) {
      print $sock "#SUGESTIONS_RELOAD#\n";
      $sock->close();
    }
  }

=pod
[global]
1145=1065,1024
1146=1103,1490,1500,1094,1093,1065

[0]
1146=1103,1490,1500,1094,1093,1065
[1]
1145=1065,1024
=cut

  #print Dumper($sug);
}
else {
  die "This script needs to be executed on the server machine...";
}

