#!/usr/bin/perl

use strict;
use CGI qw/:standard/;
use LWP::UserAgent;
use utf8;
use List::Util qw(shuffle);

# 1. http://en.wikipedia.org/wiki/Special:Random

my $ua = LWP::UserAgent->new(requests_redirectable => ["GET"]);
$ua->timeout(5);

my $q = new CGI;

my $things = [shuffle(@{getThingsFromWikipedia()})];

my $errors = [];
if (scalar @$things < 25) {
    push (@$errors, "Hmmm, had some trouble getting those 25 things");
}

my $new = $q->url();

my $errorsBox = @$errors ? "<div class='error span-7'>".join("<br/>", @$errors)."</div>" : "";

# this is a fucking mess!  rewrite this using real templates, mother fucker!

my $ht =<<EOH
<h1>25 Random Things About Me</h1>
<p>Rules: Once you've been tagged, you are supposed to write a note
with 25 random things, facts, or goals about you. At the end, choose
25 people to be tagged. You have to tag the person who tagged you.
If I tagged you, it's because I want to know more about you.
</p>
EOH
;

my $htthings = "<ol>";
foreach my $thing (@$things) {
    $htthings .= "<li>$thing</li>\n";
}
$htthings .= "</ol>";


print "Content-type: text/html\n\n";

# yuck!

print <<END_OF_TEMPLATE2
<html xmlns:fb="http://www.facebook.com/2008/fbml">
    <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <meta http-equiv="Content-language" content="en" />
        <meta name="keywords" content="random 25 things facebook meme generator" />
        <!-- Framework CSS -->
        <link rel="stylesheet" href="/blueprint/screen.css" type="text/css" media="screen, projection">
        <link rel="stylesheet" href="/blueprint/print.css" type="text/css" media="print">
        <!--[if IE]><link rel="stylesheet" href="/blueprint/ie.css" type="text/css" media="screen, projection"><![endif]-->
	
        <!-- Import fancy-type plugin for the sample page. -->
        <link rel="stylesheet" href="/blueprint/plugins/fancy-type/screen.css" type="text/css" media="screen, projection">
        <title>25 things about me</title>
    </head>
<body>
    <div class='container'>
        <div id="header">
            <h2 class="alt">25 Random Things About Me</h2>
            <div id="nav">
                  <a href='$new'><strong>another 25 things</strong></a>
                |  by <strong>kld</strong>
                | also check out <a href="/p/cover.pl">random album cover generator</a>
            </div>
        </div>
        
        <div class='top-1 span-13'>
            <style type="text/css">
                #nav {
                    position: absolute;
                    top: 5px;
                    left: 360;
                    display: block;
                }
                #header {
                    position: absolute;
                    top: 0px;
                    left: 0px;
                    width: 100%;
                    height: 30px;
                    background: #ddd;
                    border-bottom: 1px solid black;
                }
            </style>
        </div>
        
            <table style="position:absolute; top:60px; left:20px; width:480px;">
                <tr><td>
			$ht
            $htthings
                </td></tr>
            </table>
            
            <table style="position:absolute; top:60px; left:520px;">
                <tr><td>
                    $errorsBox
                    <p class="span-7">
                        This page randomly generates completely fake lists
						of 25 facts, all pulled from your friendly wikipedia.
                        <br />
                    </p>
                    <p class="span-7">
                        Click <a href="$new">this link</a> to generate a few to get the gist.
                        <br />
                    </p>
                    
                    <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"></script>

                    <fb:comments width="380"></fb:comments>

                    <script type="text/javascript">
                    FB.init("07bf17d502bd23ae3a82d911ae523c27", "/p/xd_receiver.htm");
                    </script>
     				<hr width="200">               
                    <script type="text/javascript"><!--
                    google_ad_client = "pub-2650367768277418";
                    /* Covers 468x60, created 3/1/09 */
                    google_ad_slot = "4468679137";
                    google_ad_width = 468;
                    google_ad_height = 60;
                    //-->
                    </script>
                    <script type="text/javascript"
                    src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
                    </script>
                    
                </td></tr>
            </table>    

    </div>
    
    
    
    <script type="text/javascript">
    var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
    document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
    </script>
    <script type="text/javascript">
    try {
    var pageTracker = _gat._getTracker("UA-7709074-1");
    pageTracker._trackPageview();
    } catch(err) {}</script>
    </body>
</html>
END_OF_TEMPLATE2
;    

#-----

sub getThingsFromWikipedia {   
    my $things = [];
    my $tries = 0;
    while (1) {
        my $page = randomWikipediaPage();
        $tries++;
        unless ($page) {
            last if $tries > 7;
            next;
        }
        my $facts = factsFromPage($page);
        if (scalar @$facts > 0) {
            push @$things, @$facts;
            last if scalar @$things >= 25;
        }
    }
    
    # munge the things
    
    my $finalThings = [];
    
    while (scalar @$finalThings < 25) {
        my $aFact = shift @$things;
        
        my $r = int(rand(4));
        
        if ($r == 1) {
            $aFact =~ s/ is / was /g;
            $aFact = "I was ".$aFact;
            $aFact =~ s/ (his|her|its) / my /g;
            $aFact =~ s/ (he|she|it) / I /g;
        } elsif ($r == 2) {
            $aFact =~ s/ is / am /g;
            $aFact = "I have never been ".$aFact;
            $aFact =~ s/ (his|her|its) / my /g;
            $aFact =~ s/ has / had /g;            
        } elsif ($r == 3) {
            $aFact = "Someone in my family was ".$aFact;
            $aFact =~ s/ is / was /g;
        } elsif ($r == 0) {
            $aFact = "One of my fave things in the world is ".$aFact;
        } else {
            $aFact = "As a child, I was ".$aFact;
        }
        if (length($aFact) > 200) {
            $aFact = substr($aFact, 0, 200)."...";
        }
        push @$finalThings, $aFact;
    }
    return $finalThings;
}

sub randomWikipediaPage {
    my $response = $ua->get("http://en.wikipedia.org/wiki/Special:Random");
    if ($response->is_success()) {
        return $response->content;
    }
    return undef; 
}

sub factsFromPage {
    my ($page) = @_;
    
    # strip off the header goop
    $page =~ s/[\t\r\n]/ /gm;
    $page =~ s/.*<div id="bodyContent">//gm;
    $page =~ s/<div id="column-one">.*//gm;
    
    # strip out paragraphs
    my $facts = [];
    my $fact;
    while ($page =~ / is (.*?)\.[< ]/gm) {
        next unless $1;
        my $m = $1;
        next if ($m =~ />stub</);
        # strip tags
        $m =~ s/<[^>]+(>|$)//mg;
        push @$facts, $m;
    }
    return $facts;
}

