package Apache::StockReport;

use strict;
use diagnostics;

use Apache::Constants qw(OK);
use Apache::DBI;
use Apache::Session::DBI;
use GIFgraph::linespoints;

sub handler {
    # Get the Apache request object
    my $r = shift;

    # Recover the user's session, if it exists
    my $id = $r->header_in('Cookie');
    $id =~ s|SESSION_ID=(\w*)|$1|;

    my %session;
    tie %session, 'Apache::Session::DBI', $id,
    {
     DataSource => 'dbi:mysql:test:localhost:3306',
     UserName   => '',
     Password   => ''
    };

    # Connect to the database
    my $dbh = DBI->connect("DBI:mysql:test");

    # Output a useful HTTP header, with the session cookie
    my $session_cookie = "SESSION_ID=$session{_session_id};";
    $r->header_out("Set-Cookie" => $session_cookie);
    $r->content_type("text/html");
    $r->send_http_header;

    # ------------------------------------------------------------
    # Iterate through each symbol-shares pair.  For each pair, we
    # retrieve the appropriate information from the StockValues table

    $r->print('<HTML>', "\n");
    $r->print("<Head><Title>Stock report for $session{name}</Title></Head>\n");
    $r->print('<Body>', "\n");

    $r->print("<H1>Stock report for $session{name}</H1>\n");

    # Provide a link for changing profile
    $r->print('<P><a href="/stock-profile">Change your profile</a>', "\n");

    # Print the current portfolio, or a message if the user does
    # not have one.
    my $portfolio_ref = $session{portfolio};

    if ($portfolio_ref)
    {
	my %portfolio = $portfolio_ref ? %{$portfolio_ref} : ();

	foreach my $symbol (sort keys %portfolio)
	{
	    # Ignore blank ones
	    next if ($symbol eq "");

	    my $shares = $portfolio{$symbol};
	    my (@values, @dates, @holdings);

	    # Retrieve information about this symbol from StockValues
	    # Create the query
	    my $sql = "SELECT value,date FROM StockValues ";
	    $sql .=   "WHERE symbol = \"$symbol\" ";
	    $sql .=   "ORDER BY date ";

	    # Prepare the query
	    my $sth = $dbh->prepare($sql);
	    if (!$sth)
	    {
		$r->print("<P>Error preparing query.</P>");
		$r->print("<P>SQL was \"$sql\".</P>\n");
		$dbh->disconnect;
		return OK;
	    }

	    # Send the query
	    my $result = $sth->execute;
	    if (!$result)
	    {
		$r->print("<P>Error executing query.</P>");
		$r->print("<P>SQL was \"$sql\".</P>\n");
		$sth->finish;
		$dbh->disconnect;
		return OK;
	    }

	    # Retrieve results
	    if ($sth->rows)
	    {
		while (my $row = $sth->fetchrow_arrayref)
		{
		    my ($value, $date) = @{$row};
		    push @values, $value;
		    push @dates, $date;
		    push @holdings, ($value * $shares);
		}

		# ------------------------------------------------------------
		# Create the graph for a single share
		# Put the data in an array
		my @data = (\@dates, \@values, \@holdings);

		# Create a graph with @data, and write it to a file
		my $graph = new GIFgraph::linespoints;

		# Set some options for the graph
		$graph->set('two_axes' => 1,
			   'y_label' => "Price of $symbol in dollars",
			   'x_labels_vertical' => 1);
		$graph->set_legend("Values for $symbol (left scale)",
				   "Holdings ($shares shares, right scale)");

		# Save the graph to a file
		my $random = int rand 1_000_000;
		my $filename = "/stock-images/$$-$symbol-$random.gif";
		my $path = "/usr/local/apache/htdocs/";
		$graph->plot_to_gif("$path/$filename", \@data);

		# Now refer to that graphic file
		$r->print("<H1>$symbol</H1>\n");
		$r->print("<P><img src=\"$filename\"></P>\n");
	    }
	    else
	    {
		$r->print("<P>No values for $symbol.</P>\n");
	    }
	}
    }

    # If there are no holdings, then tell the user so.
    else
    {
	$r->print("<P>Sorry, but you don't have any holdings.</P>\n");
    }

    # Finish up the HTML
    $r->print('</Body></HTML>', "\n");
    return OK;
}

1;

