#!perl

HELP "<productID>" => "Look up products from database";
HELP "edit" => "Edit product list";

my $filename = 'revbank.products';

sub _read_products {
    open my $fh, '<', $filename or die "$filename: $!";
    my %products;
    while (readline $fh) {
        /^\s*#/ and next;
        /\S/ or next;
        chomp;
        my ($ids, $p, $d) = split " ", $_, 3;
        my @ids = split /,/, $ids;

        $products{ $_ } = { id => $ids[0], price => $p, description => $d}
            for @ids;
    }

    return \%products;
}

sub command :Tab(edit,&tab) {
    my ($self, $cart, $command) = @_;

    if ($command eq 'edit') {
        system $ENV{EDITOR} || 'vi', $filename;
        return ACCEPT;
    }

    my $product = _read_products->{ $command } or return NEXT;

    my $price = parse_amount( $product->{price} ) or return NEXT;

    $cart->add(
        undef,
        -$price,
        $product->{description},
        { product_id => $product->{id} }
    );
    return ACCEPT;
}

sub tab {
    return grep /\D/, keys %{ _read_products() };
}