#!perl

use Net::MQTT::Simple "mosquitto.space.revspace.nl";

sub hook_checkout($class, $cart, $user, $transaction_id, @) {
    my $filename = "revbank.sales";
    my @entries = $cart->entries('product_id') or return;
    my %already_retained;

    # XXX: hook_checkout is called while the global lock is held, and the
    # potentially slow network traffic could make that take quite long.
    my %stats = eval { map { split " ", $_, 2 } slurp $filename };

    $stats{ $_->attribute('product_id') } += $_->quantity for @entries;

    for (@entries) {
        my $product = $_->attribute('product_id');

        publish "revspace/bank/sale" => $product;
        next if $already_retained{ $product };

        retain "revspace/bank/$product" => $stats{$_->attribute('product_id')};
        $already_retained{ $product } = 1;
    }

    spurt $filename, map {
        sprintf "%-16s %9d\n", $_, $stats{$_}
    } sort keys %stats;
}