#!/usr/bin/perl
use warnings;
use strict;
use lib ".";
use Data::Dumper qw(Dumper);
use POE;
use CM::POETools qw(requestData);
use JSON;

$SIG{__DIE__} = \&confess;

POE::Session->create(
   inline_states => {
      _start  => sub {
         my ($kernel, $heap) = @_[KERNEL, HEAP];
         requestData($_[SESSION]->ID(), "adbgui://10.11.90.10:4716/WLANTIMES", "getdone", undef, {
            auth => ["Administrator", "a"],
         });
      },
      getdone => sub {
         my ($kernel, $session, $heap, $input) = @_[ KERNEL, SESSION, HEAP, ARG0];
         my $json = undef;
         eval {
            $json = from_json($input);
         };
         if ($@ || !$json) {
            print "ERROR: ".$@.": ".$input."\n";
         } elsif($json->{result} eq "ok") {
            $heap->{ticketdata} = $json->{data};
            $kernel->yield("processtickets");
         } else {
            print "ADBGUI remote error: ".$json->{error}."\n";
         }
      },
      processtickets => sub {
         my ($kernel, $heap, $input) = @_[KERNEL, HEAP, ARG0];
         (my $ticket) = (keys %{$heap->{ticketdata}});
         if ($heap->{running}++) {
            my $json = undef;
            eval {
               $json = from_json($input);
            };
            if ($@ || !$json || ($json->{result} ne "ok")) {
               print " -> FAILED\n";
            } else {
               print " -> OK: ".$json->{id}."\n";
            }
         }
         return
            unless $ticket;
         print "Processing ".$ticket;
         requestData($_[SESSION]->ID(), "adbgui://127.0.0.1:4716/UPDATE", "processtickets", undef, {
            auth => ["admin", "uxxnwssb"],
         }, {
            id                     => $ticket,
            table                  => "tickets",
            columns => {
               "tickets.nutzungszeit" => $heap->{ticketdata}->{$ticket},
            },
         });
         delete $heap->{ticketdata}->{$ticket};
      },
   }
);

$poe_kernel->run();
