#!/usr/bin/perl

use strict;
use warnings;
use XML::LibXML;
use XML::LibXML::XPathContext;
use HTTP::Lite;
use MIME::Base64;
use Encode;
use threads;
use threads::shared;
use URI::Escape;

# 設定
my $username = '';
my $password = '';
my $intervaltime = 60;

my @talkTwitterQueue : shared = ();
my $th_getTwitter = threads->new (\&getTwitter);
my $th_postTwitter = threads->new (\&postTwitter);
#my $th_talkTwitter = threads->new (\&talkTwitter);
&talkTwitter();

# 本体
sub getTwitter {
	my $twitteruri = 'http://twitter.com/statuses/friends_timeline.xml';
	my $newesttextid;
	while (1) {
		my $http = HTTP::Lite->new();
		$http->{'method'} = 'GET';
		$http->add_req_header ("Authorization", "Basic ".encode_base64("$username:$password"));
		my $requri;
		if (defined $newesttextid) {
			$requri = $twitteruri."?since_id=".$newesttextid;
		} else {
			$requri = $twitteruri;
		}

		if (not $http->request ($requri)) {
			print ("error at request");
		} else {
			my $parser = XML::LibXML->new();
			my $doc = $parser->parse_string ($http->body());
			my $xpc = XML::LibXML::XPathContext->new ($doc);
			my @statuses = $xpc->findnodes ('/statuses/status');
			foreach my $status (reverse @statuses) {
				my $xpc2 = XML::LibXML::XPathContext->new ($status);
				my $name = $xpc2->find ('user/name/text()');
				my $text = $xpc2->find ('text/text()');
				my $id   = $xpc2->find ('id/text()');
				if ((not defined $newesttextid) or (int($newesttextid) < int($id))) {
					$newesttextid = $id;
				}

				my $mes = $name.decode("shiftjis","のつぶやき　").$text;
				push @talkTwitterQueue, $mes;
			}
		}
		sleep ($intervaltime);
	}
}

sub postTwitter {
	while (<>) {
		chomp;
		my $status = decode ("shiftjis", $_);
		my $post = uri_escape_utf8 ($status);
		my $http = HTTP::Lite->new();
		$http->{'method'} = 'POST';
		$http->add_req_header ("Authorization", "Basic ".encode_base64("$username:$password"));
		my $requri = 'http://twitter.com/statuses/update.xml?source=twittertalk&status='.$post;

		if (not $http->request ($requri)) {
			print ("error at request");
		} else {
			my $mes = $status . decode ("shiftjis", "　というステータスを投稿しました。");
			push @talkTwitterQueue, $mes;
		}
	}
}

sub talkTwitter {
	while (1) {
		while (@talkTwitterQueue) {
			my $mes = encode ("shiftjis", shift @talkTwitterQueue);
			print $mes."\n";
			system ("SofTalk.exe", $mes);
		}
		sleep (1);
	}
}
