use zUtil;

sub alphaVantageHandler
{
    $html = shift;
    $symbol = shift;
    my( @rValue ) = ();
    my( $table, $infoRow, $value, $change, $row );
    my( $done, $date, $link, $headline, $source );
    my( %results, $results );
    my( $headlineIndex, $stockIndex );

    
    print "------------------ alphaVantageHandler ($symbol) --------------------\n";
    print "$html\n";
    #sleep 5;
    #exit 1;
    
    # timestamp,open,high,low,close,volume
    # 2017-09-08 16:00:00,6359.2364,6362.2002,6357.8851,6360.7605,0
        
    # http://www.jarloo.com/real-time-google-stock-api/
    # look up symbols here, i.e. for nasdaq  https://www.google.com/finance?q=NASDAQ

    $change = "n/a";
    $last = "n/a";

    $first_line=( split /\n/, $html )[1];
    print "first: $first_line\n\n";

    if( $first_line =~ /(.*?),(.*?),(.*?),(.*?),(.*?),(.*?)/gsi )
    {        
        $close = $5;
        $open = $2;
        #$close =~ s/\..*$//gs;
        #$open =~ s/\..*$//gs;
        $close = sprintf("%.2f", $close);
        $open = sprintf("%.2f", $open);

        print "open: $open\n";
        print "close: $close\n";

        $change_value = $close - $open;

        if( $change_value >= 0) {
            $change_percent = sprintf("%.2f", (($close - $open)/$close)*100);
            $change = sprintf("+%.2f (%s)", $change_value, $change_percent);
        } else {
            $change_percent = sprintf("%.2f", (($open - $close)/$close)*100);
            $change = sprintf("%.2f (%s)", $change_value, $change_percent);
        }

        print "change: $change\n";
    }

    push @rValue,
    {
        'change' => $change,
        'last' => $close
    };
    undef( $change );
    undef( $value );

    return @rValue;
}

return 1;

