#!/usr/bin/env python
from util import *
import psycopg, time, re, random
ParenRx = re.compile(r'\(.*?\)')
db = psycopg.connect('dbname=thokbook')

def esc(x):
    return x.replace('&', '&amp;').replace("'", "&#x27;")
    
print "<books version='0' date='%s'>" % time.ctime()
cursor = db.cursor()
cursor.execute('''
SELECT books.isbn, shelf, title, authors, url, imageurlmedium, rating, comment
  FROM books, asin
  WHERE books.isbn = asin.isbn
  ORDER BY shelf ASC
''')

l = cursor.fetchall()
shelves={}
for x in l:
    shelves.setdefault(x[1], []).append(x)

shlist = shelves.keys(); shlist.sort()

for shelf in shlist:
    print "<shelf name='%s'>" % shelf
    # Find "featured" books
    # Sort by rating, then by random element
    l = shelves[shelf]
    l = stableDSU(l, lambda x: (-(x[6] or 0), random.random()))
    l = l[:10]; random.shuffle(l)
    featured = makedict([x[0] for x in l[:5]])
    
    for isbn, _, title, authors, url, image, rating, comment in shelves[shelf]:
        rating = rating or 0

        #if title.lower().startswith('the '):
        #            title = title[4].upper() + title[5:] + ', %s' % title[:4].lower()
        
        fulltitle, fullauthors = title, authors
        print "<book isbn='%s' rating='%d' featured='%d'>" % (isbn, rating, featured.has_key(isbn))
        title = ParenRx.sub('', title)
        if len(title)> 50 and ':' in title:
            title = title[:title.find(':')]
        if len(title) > 70:
            title = title[:70] + "..."
        if ',' in authors:
            authors = authors[:authors.find(',')] + ' et al'
        for field in 'authors', 'title':
            print "<%s abbrev='%s'>%s</%s>" % (field, esc(locals()[field]), esc(locals()['full' + field]), field)

        for field in 'url', 'image':
            print "<%s>%s</%s>" % (field, locals()[field], field)
        print "</book>"
    print "</shelf>"
print "</books>"

