#!/usr/bin/env python
__doc__="""
This will fetch up to 15 items from del.icio.us for the given
username and tag(s) and make a little 3x5 index card PDF 
suitable for printing.

If you don't provide both username and tags, it'll just default to
grabbing mine. And since I built this script to make a reading list,
you'll get a list of book titles & authors.

usage: what-to-read.py username tags

Thanks to effbot for the nice little del.icio.us script and inspiration.
"""

import urllib, sys
from reportlab.lib.units import inch
from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer
from reportlab.lib.styles import ParagraphStyle, StyleSheet1

def utf8(s):
    return unicode(s, "utf-8")

class Post(object):
    def __init__(self, item):
        self.link = utf8(item["u"])
        self.title = utf8(item["d"])
        self.tags = map(utf8, item["t"])

def getposts(user, tag="", count=15):
    if isinstance(tag, tuple):
        tag = "+".join(tag)
    url = "http://del.icio.us/feeds/json/%s/%s?raw&count=%d" % (user, tag, count)
    return map(Post, eval(urllib.urlopen(url).read()))

def build_pdf(username="gavin", tags="readinglist"):
	styles = StyleSheet1()
	styles.add(ParagraphStyle(
	    name='Normal',
	    fontName='Helvetica',
	    fontSize=8,
	    leading=10))

	styles.add(ParagraphStyle(
	    name='Definition',
	    parent=styles['Normal'],
	    firstLineIndent=0,
	    leftIndent=.125*inch,
	    spaceBefore=0,
	    spaceAfter=2,
	    bulletFontName='Helvetica',
	    bulletFontSize=8,
	    bulletIndent=0))

	pdf = SimpleDocTemplate("readinglist.pdf", pagesize=(3*inch, 5*inch),
	                                           leftMargin=.125*inch, rightMargin=.125*inch, 
	                                           topMargin=.125*inch, bottomMargin=.125*inch)

	booklist = []
	for book in getposts(username, tags):
	    line = []
	    line.append("<bullet>o</bullet>")
	    book_title = book.title.strip()
	    t = book_title.rfind(':') + 1 # want to include last ':'
	    print_title = book_title.replace(book_title[:t], "<b>" + book_title[:t] + "</b>")
	    line.append(print_title)
	    para = Paragraph("".join(line), styles["Definition"])
	    booklist.append(para)

	pdf.build(booklist)
	print "Done!"


if __name__ == '__main__':
    if len(sys.argv) == 3:
        username = sys.argv[1]
        tags = sys.argv[2]
        build_pdf(username, tags)
    else:
        print __doc__
        print "Building list using username: gavin, tags: readinglist."
        build_pdf()


