#!/usr/bin/perl
use strict;
#use warnings;
use vars qw($VERSION %IRSSI);
use Irssi qw(signal_add_last command_bind);
use List::Util qw(first);
use XML::Simple;
use Data::Dumper;
use LWP::Simple; 

$VERSION = '1.0';
%IRSSI = (
  authors     => 'John Anderson',
  contact     => 'sontek@gmail.com',
  name        => 'Twitter',
  description => 'Allows you to update twitter from irssi',
  license     => 'X11/MIT',
  url         => 'http://blog.sontek.net'
);
# configuration
my $username = "USERNAME"; 
my $password = "PASSWORD";

my $xml = new XML::Simple (KeyAttr=>[]);

sub get_complete_list {
    # Twitter API URL's
    my $followers_url="http://$username:$password\@twitter.com/statuses/followers.xml";
    my $friends_url="http://$username:$password\@twitter.com/statuses/friends.xml";
   
    # Download and parse the XML files into arrays 
    my %friends=parse_xml($friends_url);
    my %followers=parse_xml($followers_url);
    my %complete_list = %friends;

    # Clean out dupes
    for my $key ( keys %followers) {
        if(!$complete_list{$key}) {
            $complete_list{$key} = 1;
        }
    }

    return keys %complete_list;
}

sub parse_xml {
    # Grabs all users from the xml file and returns an array
    my ($url) = @_;

    my $page=1;
    my %list = ();
    do {
        my $current_url = $url . "?page=$page";
        my $content = get($current_url);
        my $data = $xml->XMLin($content);

        foreach my $e (@{$data->{user}})
        {
            $list{$e->{screen_name}} = 1;
        }
        my $size = @{$data->{user}};
        my $more_pages = (($size * $page) / 100);

        if($more_pages < 1)
        {
            $page=-1;
        }
        else
        {
            $page++;
        }

    } while($page != -1);

    return %list;
} 

# Pull the list when irssi first loads
my @friends = get_complete_list();

sub sig_complete {
  my ($complist, $window, $word, $linestart, $want_space) = @_;
  # matches the irssi text with our user list
  # todo: append @ in front of the name
  my $prefix = substr($word, 0, 1);
  my $match = $word;
  if($prefix eq "@") {
      $match = substr($word, 1);
  }

  my @matches = grep /^$match/i, @friends;

  if($prefix eq "@") {
    @matches = map { "\@$_" } @matches; 
  }
  push @$complist, @matches;
  return;
}

# Usage: /twitter <cmd> args 
sub cmd_twitter {
  # data - contains the parameters for /twitter
  # server - the active server in window
  # witem - the active window item (eg. channel, query)
  #         or undef if the window is empty

  my ($data, $server, $witem) = @_;

  if ($data) {
    my ($command, $message) = split(/ /, $data, 2);
    if($command eq "u") {
        my $update_url = "http://$username:$password\@twitter.com/statuses/update.xml";
        if($message) {
            my $ua = new LWP::UserAgent; 
            my $response = $ua->post($update_url, { status=>$message });
            my $content = $response->content;
        } else {
            Irssi:print("You must provide a message to update with");
        }
        #TODO: Check response, report error to user if there was one.
    }
    elsif ($command eq "d") {
        my $direct_url = "http://$username:$password\@twitter.com/direct_messages/new.xml";
        my ($user, $text) = split(/ /, $message, 2);

        if($user && $text) {
            my $ua = new LWP::UserAgent; 
            my $response = $ua->post($direct_url, { user=>$user, text=>$text });
            my $content = $response->content;
        } else {
            Irssi:print("You need to provide the user to message and text to send");
        }
        #TODO: Check response, report error to user if there was one.
    }
    else {
        print "in command else";
    }
  } else {
    Irssi::print("You need to include a command");
  }

} 

command_bind('twitter', 'cmd_twitter');
signal_add_last 'complete word' => \&sig_complete;
