"""
twitter.py: written by Scaevolus 2009
retrieves most recent tweets
"""

import re
import urllib2
from lxml import etree

from util import hook


def unescape_xml(string):
    # unescape the 5 chars that might be escaped in xml

    # gratuitously functional
    # return reduce(lambda x, y: x.replace(*y), (string,
    #     zip('&gt; &lt; &apos; &quote; &amp'.split(), '> < \' " &'.split()))

    # boring, normal
    return string.replace('&gt;', '>').replace('&lt;', '<').replace('&apos;',
                    "'").replace('&quote;', '"').replace('&amp;', '&')


@hook.command
def twitter(inp):
    ".twitter <user>/<id> - gets last tweet from <user>/gets tweet <id>"
    inp = inp.strip()
    if not inp:
        return twitter.__doc__

    getting_id = False
    if re.match('^\d+$', inp):
        getting_id = True
        url = 'http://twitter.com/statuses/show/%s.xml' % inp
    elif re.match('^\w{,15}$', inp):
        url = 'http://twitter.com/statuses/user_timeline/%s.xml?count=1' % inp
    else:
        return 'error: invalid username'

    try:
        xml = urllib2.urlopen(url).read()
    except urllib2.HTTPError, e:
        errors = {400 : 'bad request (ratelimited?)',
                401: 'tweet is private',
                404: 'invalid user/id',
                500: 'twitter is broken',
                502: 'twitter is down ("getting upgraded")',
                503: 'twitter is overloaded (lol, RoR)'}
        if e.code == 404:
            return 'error: invalid ' + ['username', 'tweet id'][getting_id]
        if e.code in errors:
            return 'error: ' + errors[e.code]
        return 'error: unknown'

    tweet = etree.fromstring(xml)

    if not getting_id:
        tweet = tweet.find('status')
        if tweet is None:
            return 'error: user has no tweets'

    return unescape_xml(': '.join(tweet.find(x).text.replace('\n', '') for x in
        'created_at user/screen_name text'.split()))

@@ -116,16 +116,52 @@
 rt etree
+%0Afrom time import strptime, strftime
 %0A%0Afrom u
@@ -653,16 +653,27 @@
 %3Cuser%3E/%3C
+user%3E %3Cn%3E/%3C
 id%3E - ge
@@ -679,16 +679,22 @@
 ets last
+/%3Cn%3Eth
  tweet f
@@ -791,16 +791,41 @@
 _doc__%0A%0A
+%0A    getting_nth = False%0A
     gett
@@ -911,35 +911,16 @@
  url = '
-http://twitter.com/
 statuses
@@ -995,27 +995,263 @@
  = '
-http://twitter.com/
+statuses/user_timeline/%25s.xml?count=1' %25 inp%0A    elif re.match('%5E%5Cw%7B,15%7D%5Cs+%5Cd+$', inp):%0A        getting_nth = True%0A        name, num = inp.split()%0A        if int(num) %3E 3200:%0A            return 'error: only supports up to the 3200th tweet'%0A        url = '
 stat
@@ -1279,31 +1279,47 @@
 .xml?count=1
-' %25 inp
+&page=%25s' %25 (name, num)
 %0A    else:%0A 
@@ -1357,16 +1357,59 @@
 sername'
+%0A    %0A    url = 'http://twitter.com/' + url
 %0A%0A    tr
@@ -2112,16 +2112,48 @@
 s None:%0A
+            if getting_nth:%0A    
         
@@ -2180,57 +2180,328 @@
 ser 
-ha
+doe
 s no
- tweets'%0A%0A    return unescape_xml(': '.join
+t have that many tweets'%0A            else:%0A                return 'error: user has no tweets'%0A%0A    time = strftime('%25Y-%25m-%25d %25H:%25M:%25S', %0A             strptime(tweet.find('created_at').text,%0A               '%25a %25b %25d %25H:%25M:%25S +0000 %25Y'))%0A    screen_name = tweet.find('user/screen_name').text%0A    text = unescape_xml
 (twe
@@ -2508,17 +2508,22 @@
 et.find(
-x
+'text'
 ).text.r
@@ -2542,43 +2542,43 @@
  '')
- for x in%0A        'created_at user/
+)%0A%0A    return %22%25s %25s: %25s%22 %25 (time, 
 scre
@@ -2588,21 +2588,12 @@
 name
+,
  text
-'.split())
 )%0A

support '.twitter <user> <id>', closes issue #1