###########################################
package Plugger::Account;
# 2004, Mike Schilli <m@perlmeister.com>
###########################################

use strict;
use warnings;
use Term::ANSIColor qw(:constants);

###########################################
sub init {
###########################################
    my($class, $ctx) = @_;

    $ctx->register_cmd("account",
        \&start, \&process, \&finish);
}

###########################################
sub start {
###########################################
    my($ctx) = @_;

    $ctx->mem()->{account_total} = 0;
}

###########################################
sub account_start {
###########################################
    my($ctx, $name) = @_;

    print BOLD, BLUE,
          "Account: $name\n",
          RESET;

    $ctx->mem()->{account_subtotal} = 0;
    $ctx->mem()->{account_current} = $name;
}

###########################################
sub account_end {
###########################################
    my($ctx, $name) = @_;

    print  BOLD, BLUE;
    printf "%-47s %9.2f\n\n", "Subtotal:", 
           $ctx->mem()->{account_subtotal};
    print RESET;
}

###########################################
sub account_end_all {
###########################################
    my($ctx) = @_;

    print  BOLD, BLUE;
    printf "%-47s %9.2f\n\n", "Total:", 
           $ctx->mem()->{account_total};
    print RESET;
}

###########################################
sub process {
###########################################
    my($ctx, @args) = @_;

    my $c = $ctx->mem()->{account_current};
    account_end($ctx, $c) if $c;
    account_start($ctx, $args[1]);
}

###########################################
sub finish {
###########################################
    my($ctx) = @_;

    my $c = $ctx->mem()->{account_current};
    account_end($ctx, $c) if $c;
    account_end_all($ctx);
}

###########################################
sub position {
###########################################
    my($type, $ticker, $n, $at, $price,
       $value, $gain) = @_;

    unless(defined $ticker) {
        printf "%-47s %9.2f\n", 
        $type, $value;
        return;
    }

    my $clr = $gain > 0 ? GREEN : RED;

    printf "%-8s %-10s %9.3f %9.3f %7.2f" .
           " %9.2f %s(%+9.2f)%s\n",
             $type, $ticker, $n, $at,
             $price,
             $value, $clr, $gain, RESET;
}

1;
