#!/usr/bin/env perl

use strict;
use warnings;

use App::bovespa;
use Getopt::Long;

my ( $filename, $stock );

GetOptions(
    "stock=s"   => \$stock,
    "file=s"    => \$filename,
    "help"      => \&help,
);

actual_value ( $stock ) if $stock;
parse_file ( $filename ) if $filename;

help();

sub actual_value {
    my $stock_name = shift;

    my $exchange = App::bovespa->new();

    print "Actual value is " . $exchange->stock( $stock_name ) . "\n";
    exit;
}

sub parse_file {
    my $file = shift;

    die "Filename specified does not exists" if ! -e $file;

    my $exchange = App::bovespa->new();

    open my $fh, "<", $file or die "Could not open the file";
        
        printf("%8s\t%8s\t%8s\t%8s\t%8s\t%8s\t%8s\n", qw/Symbol Quantity Paid Value Total Total_Paid Diff/ );
        while ( my $line = <$fh> ){
            my ( $stock, $quantity, $paid ) = split ( /\s+/, $line );
            my ( $value, $total, $total_paid, $diff );
            $value = $exchange->stock( $stock );
            $paid =~ s/,/\./;
            $value =~ s/,/\./;
            if ( $quantity ){
                $total = $value * $quantity;
            }
            if ( $paid ) {
                $total_paid = $quantity * $paid;
            }
            if ( $total and $total_paid ){
                $diff = $total - $total_paid;
                if ( $diff < 0 ){
                    $diff = "( ". ( abs $diff ) . " )";
                }
            }
            printf("%8s\t%8s\t%8s\t%8s\t%8s\t%8s\t%8s\n",$stock, $quantity, $paid, $value, $total, $total_paid, $diff );
        }

    close $fh;
    exit;
}



sub help{
    print <<EOF;

I'm a simple tool to follow up your stocks at Bovespa Stock Exchange.
The goal is a simple follow up, the data provided is just for
reference and it is not in realtime.

You have two options:

    --stock NAME
    --file  filename

 stock: Will print the actual value of the stock, in Brazilian Real
 file: Will parse a file and will output the results, the file format
       is described as follow

File Format:
One line per stock, starts with the stock name, the quantity and the
value that you paid for it. Stock name is mandatory, the others are 
optional.

Example:
RENT3.SA 300 10.00

The output will be, assuming the value of stock being 12.00:

RENT3.SA 300 10.00 12.00 360.00 300.00 60

The first three columns will be the same, plus the actual value,
the actual total, the total paied for and the diference between 
the actual total and what you paid for.



EOF
}
