#!/usr/bin/perl -w
# use knotify to watch twitter
#
# FIXME:
# shouldn't have username & password on command line
# should remember last seen tweet
# should replace $tweet->[] with $tweet->{}
# should be smarter about putting entries in the @tweet array so that we don't have to sort it
# should have a better time format than unix time...
#
package main;

use strict;
use lib '/home/waider/src/perl';
use DCOP;
use LWP::UserAgent;
use XML::Simple;
use Date::Parse;

my ( $username, $password ) = @ARGV;
die unless $password;

my $dcop = new DCOP(
                    target => 'knotify',
                    user => $ENV{LOGNAME},
                    control => 'default',
                   );
if ( !$dcop->run()) {
    die "can't contact knotify: $!";
}

my $ua = new LWP::UserAgent;
$ua->credentials( "twitter.com:80", "Twitter API", $username, $password );

my $lastseen = 0;
my $lastcheck = 0;
my @tweets;

while ( 1 ) {
    if ( time - $lastcheck > 60 ) {
        my $req = new HTTP::Request( GET => 'http://twitter.com/statuses/friends_timeline.xml' );
        my $res = $ua->request( $req );
        if ( $res->is_success ) {
            my $content = $res->content;
            eval {
                my $xml = XMLin( $content, ForceArray => 1 );
                for my $status ( @{$xml->{status}} ) {
                    my $datestamp = str2time( $status->{created_at}->[0] );
                    if ( !defined( $datestamp )) {
                        print STDERR "can't parse $datestamp\n";
                        next;
                    }

                    if ( $datestamp > $lastseen ) {
                        my $from = $status->{user}->[0]->{screen_name}->[0];
                        my $msg = $status->{text}->[0];
                        push @tweets, [ $datestamp, $from, $msg ];
                    }
                }
                # horrible
                @tweets = sort { $a->[0] <=> $b->[0] } @tweets;
            };
            print "Error: $@\n" if $@;
        }

        $lastcheck = time;
        if ( @tweets ) {
            $lastseen = $tweets[-1]->[0];
        }
    }

    if ( @tweets ) {
        my $tweet= shift @tweets;
        $dcop->run( "notify", "New tweet", $tweet->[1] . '@' . $tweet->[0],
                    $tweet->[2], '', '', 16|64, 0 );
        printf( "%-10.10s %-69.69s\n", $tweet->[1], $tweet->[2] );
        sleep( 5 );
    } else {
        my $minsleep = time - $lastcheck;
        sleep( $minsleep ) if $minsleep > 0;
    }
}
