#!/usr/bin/python

from __future__ import with_statement

import urllib2, simplejson, subprocess
import re, textwrap

wrapper = textwrap.TextWrapper(break_on_hyphens=False, break_long_words=False)

def html_to_zephyr(c):
    c = re.sub(r'<br */?>', '\n', c)
    c = re.sub(r'<b *>([^<]+)</b *>', r'@b(\1)', c)
    c = re.sub(r'<i *>([^<]+)</i *>', r'@i(\1)', c)
    c = re.sub(r'<u *>([^<]+)</u *>', r'@i(\1)', c)
    c = re.sub(r'<span [^>]*>(.+)</span *>', r'\1', c)
    c = re.sub(r'<span [^>]*>(.+)</span *>', r'\1', c)
    c = re.sub(r'<a href="([^"]+)".*>\s*\1\s*</a>', r'\1', c)
    c = re.sub(r'<a href="([^"]+)"[^>]*>\s*([^<]+?)\s*</a>', r'\2 (\1)', c)
    c = re.sub(r'&#([\d]+);', lambda m: unichr(int(m.group(1))), c)
    c = re.sub(r'&quot;', '"', c)
    return c

def main():
    data = simplejson.load(urllib2.urlopen("https://www.googleapis.com/plus/v1/people/106067820097042125274/activities/public?key=AIzaSyBh33HYLMHiI6kAcak3afCKRuTvJxvizY8&fields=items(id%2Cannotation%2Cobject(actor%2FdisplayName%2Cattachments(content%2CdisplayName%2Cimage%2Furl%2CobjectType%2Curl)%2Ccontent%2Cid%2Curl))"))

    with open('/mit/xavid/.plus-to-lj', 'r') as fil:
        lastid = fil.read().strip()
    newlastid = None

    items = data["items"]
    for idx in xrange(len(items)):
        if items[idx]["id"] == lastid:
            items = items[:idx]
            break

    for i in reversed(items):
        if "actor" in i["object"]:
            dn = i["object"]["actor"]["displayName"]
            # continue
            title = "Reshared from %s" % dn
            reshared = True
        else:
            title = None
            reshared = False
        content = i["object"]["content"]
        url = i["object"]["url"]
        urlname = "See on Google+"

        plaincontent = html_to_zephyr(content)

        if plaincontent.strip():
            plainlines = '\n'.join(wrapper.fill(l)
                                   for l
                                   in plaincontent.split('\n')).split('\n')
        else:
            plainlines = []

        if reshared:
            content = '<blockquote>%s</blockquote>' % content
            plainlines = ['> ' + l for l in plainlines]

        if "annotation" in i:
            content = '%s\n\n%s' % (i["annotation"], content)
            plainlines = ([wrapper.fill(l)
                           for l
                           in html_to_zephyr(i["annotation"]).split('\n')]
                          + ['']
                          + (["%s:" % title] if title is not None else [])
                          + plainlines)
        
        if len(plainlines) > 20:
            plainlines = plainlines[:15]
            plainlines.append(wrapper.fill('... (%s)' % url))        
        plaincontent = '\n'.join(plainlines)

        if "attachments" in i["object"]:
            for a in i["object"]["attachments"]:
                if a["objectType"] == "photo-album":
                    if title:
                        title += ": %s" % a["displayName"]
                    else:
                        title = a["displayName"]
                    url = a["url"]
                elif a["objectType"] == "photo":
                    if "url" in a:
                        content += '\n\n<a href="%s"><img src="%s" /></a>' % (
                            a["url"], a["image"]["url"])
                    else:
                        content += '\n\n<img src="%s" />' % (a["image"]["url"])
                elif a["objectType"] == "article":
                    url = a["url"]
                    urlname = a["displayName"]
                elif a["objectType"] == "video":
                    urlname = "<b>%s</b>: %s" % (a["displayName"], a["content"])

        if not title:
            title = "Plusery"
        else:
            plaincontent = title + ':\n\n' + plaincontent
        content += '\n\n<a href="%s">%s</a>' % (url, urlname)
        if url not in plaincontent:
            plaincontent += '\n\n%s\n%s' % (urlname, url)

        print title
        if True:
            p = subprocess.Popen(['/mit/xavid/bin/charm', '-q',
                                  '-s', title,
                                  ], stdin=subprocess.PIPE)
            p.communicate(content.encode('utf-8'))
            assert p.returncode == 0

        if plaincontent is not None:
            p = subprocess.Popen(['zwrite', '-d', '-c', 'xavid', '-i', '+', 
                                  '-s', 'Plusery',
                                  ], stdin=subprocess.PIPE)
            p.communicate(plaincontent.encode('utf-8'))
            assert p.returncode == 0

        newlastid = i["id"]
        print newlastid

    if newlastid is not None:
        with open('/mit/xavid/.plus-to-lj', 'w') as fil:        
            fil.write(newlastid)

if __name__ == '__main__':
    main()
