#!/usr/bin/perl -T

# Implements MVC, as per comments.

use warnings;
use strict;
use DBI;
use CGI qw/:standard :cgi escapeHTML/;
use Time::Local;
use XML::LibXML;
use HTML::BBCode;

my $dbh = DBI->connect('not', 'telling', 'you', {RaiseError => 1, AutoCommit => 0});
open INDEX, "<", "index.template";
open FLICK, "<", "flickr/flickr.html";
my $numPosts = 5;

sub parseComments {
	my $bbc = HTML::BBCode->new();

	my $author = param('author');
	my $email = param('email');
	my $url = param('url');
	my $comment= param('comment');
	my $eight = param('eight');
	my $post_id = param('p');	

	# This is the CONTROLLER
	$eight =~ s/[^0-9]//g;
	return if ($eight != 8);

	return if (!defined $comment || (length($comment) < 2));

	if (defined $author && (length($author) > 1))
	{
		$author = $bbc->parse($author);
	} else
	{
		$author = undef;
	}

	if (defined $email && (length($email) > 1))
	{
		$email = $bbc->parse($email) ;
	} else
	{
		$email = undef;
	}

	if (($url =~ /http:\/\//) || ($url =~ /https:\/\//))
	{
		$url = $bbc->parse($url);
	} else
	{
		$url = undef;
	}

	$comment = $bbc->parse($comment);

	eval {
		my $sql = qq{
				INSERT INTO blog.comment (post_id, author, timestamp, email, url, comment) VALUES (?, ?, now(), ?, ?, ?)
		};
		$dbh->do($sql, undef, $post_id, $author, $email, $url, $comment);
		$dbh->commit();
	};
	if ($@)
	{
		# This is the MODEL
		$dbh->rollback();
	}
}

sub commentBlock {
	my ($post_id, $main_post_id) = @_;

	my $sql = qq{
		SELECT 	comment_id, 
				TO_CHAR(timestamp, 'FMDD FMMon YYYY, HH24:MI AM'),
				author, url, comment
		FROM blog.comment
		WHERE post_id = ?
		ORDER BY timestamp 
	};

	my $comments = $dbh->selectall_arrayref($sql, undef, $post_id);
	my $nComments = scalar(@$comments);

	my $ret = qq{
		<a href="javascript:showComment($post_id)">Comments ($nComments)</a> <br />
	};

	if (($post_id == $main_post_id) && defined(param('comment')))
	{
		$ret = $ret . qq{
			<div class="comments" id="comment-$post_id" style="display: ">
		};
	} else
	{
		$ret = $ret . qq{
			<div class="comments" id="comment-$post_id" style="display: none">
		};
	}

	foreach my $r (@$comments)
	{
		my ($comment_id, $timestamp, $author, $url, $comment) = @$r;		
		my $link;

		$author = "Anonymous" if (!defined $author);

		if (defined $url && (length($url) > 7))
		{
			$link = qq{<a href="$url">$author</a>};
		} else
		{
			$link = $author;
		}

		$ret = $ret . qq{
			<div class="comment">
				<h2>$link - $timestamp</h2>
				<blockquote>
					$comment
				</blockquote>
			</div>
		}
	}

	my $display = "none";
	$display = "" if ($nComments == 0);

	$ret = $ret . qq{
			<a href="javascript:showCommentEntry($post_id)">--&gt;Add comment</a> <br />
			<div class="comment-entry" id="comment-entry-$post_id" style="display: $display">
			<form action="index.cgi" method="post">
				<label for="author">Name</label>
				<input type="text" name="author" /> <br />
				<label for="email">Email</label>
				<input type="text" name="email" /> <br />
				<label for="url">URL</label>
				<input type="text" name="url" value="http://" /> <br />
				<label for="eight">1+7=</label>
				<input type="text" name="eight" /> <br />
				<input type="hidden" name="p" value="$post_id" />
				<h2>NB: Only <a href="http://www.phpbb.com/community/faq.php?mode=bbcode">bbcode</a> allowed.</h2>
				<textarea cols="50" rows="10" name="comment"></textarea> <br />
				<input type="submit" value="post" />
			</form>
			</div>
	</div>
	};

	return $ret;
}

my $post_id = 0;
if (param())
{
	$post_id = param('p');	
	$post_id =~ s/[^0-9]//g;
	
	parseComments() if (defined param('comment'));
}

print header;


my $sql = qq{
	SELECT 
		post_id, 
		title, 
		TO_CHAR(timestamp, 'FMDD FMMon YYYY, HH24:MI AM'),
		content, author
	FROM blog.post 
	WHERE post_id <= ? AND NOT draft
	ORDER BY timestamp DESC
	LIMIT ? 
	};
my $post = $dbh->selectall_arrayref($sql, undef, $post_id, $numPosts);

if (!defined @$post[0])
{
	($post_id) = $dbh->selectrow_array("SELECT MAX(post_id) FROM blog.post");

	$sql = qq{
	SELECT 
		post_id, 
		title, 
		TO_CHAR(timestamp, 'FMDD FMMon YYYY, FMHH12:MI AM'),
		content, author
	FROM blog.post 
	WHERE NOT draft
	ORDER BY timestamp DESC
	LIMIT ?
	};
	$post = $dbh->selectall_arrayref($sql, undef, $numPosts);
}

my @rows = @$post;

my ($prev_post_id, $prev_title) = $dbh->selectrow_array ("SELECT post_id, SUBSTRING(COALESCE(title, 'untitled ' || post_id) FROM 1 FOR 20) FROM blog.post WHERE post_id < ? AND NOT draft ORDER BY post_id DESC LIMIT 1", undef, $post_id);
my ($next_post_id, $next_title) = $dbh->selectrow_array ("SELECT post_id, SUBSTRING(COALESCE(title, 'untitled ' || post_id) FROM 1 FOR 20) FROM blog.post WHERE post_id > ? AND NOT draft ORDER BY post_id LIMIT 1", undef, $post_id);

my $posts;
foreach my $r (@rows)
{
	my ($sub_post_id, $title, $timestamp, $content, $author) = @$r;

	$content =~ s/<h1>.*?<\/h1>//i;
		
	my $comment = commentBlock($sub_post_id, $post_id);
	$comment = '' if (!defined $comment);
	$posts = $posts . qq{<h1>$title</h1><h2>$timestamp</h2><div class="blog">$content <br /> $comment </div>\n};
}


while (<INDEX>)
{
	my $line = $_;

	# This is the VIEW
	if ($line =~ m/##POSTS##/)
	{
		print $posts;
	} 
	elsif ($line =~ m/##NAV##/)
	{
		print qq{<a href="index.cgi?p=$prev_post_id">$prev_title</a>&lt;&lt;&lt;} if (defined $prev_post_id);
		print qq{&nbsp;|&nbsp;};
		print qq{&gt;&gt;&gt;<a href="index.cgi?p=$next_post_id">$next_title</a>} if (defined $next_post_id);
	}
	elsif ($line =~ m/##FLICKR##/)
	{
		my $lncnt = 1;
		while (<FLICK>)
		{
			print $_;
			$lncnt ++;
			last if $lncnt > 12 * 2;
		}		
	} else
	{
		print $line;
	}
	
}

