import time
import urllib
import locale
import Image, ImageFont, ImageDraw

fg='#686868' #dark grey
bg='#EDEDED' #light grey
username='CSkaryd'
fontsize=22
fontfile='Handel_Gothic_BT.ttf'

locale.setlocale(locale.LC_ALL, "")


def getUserInfo(username):
  data=urllib.urlopen('http://ws.audioscrobbler.com/1.0/user/%s/profile.xml' % username).readlines()
  data=''.join(data)

  start = data.find('<playcount>') + len('<playcount>')
  end = data.find('</playcount>')
  playcount = int(data[start:end])

  start = data.find('<registered')
  end = data.find('</registered>')
  reg=data[start:end]
  regformatted=reg[reg.find(">")+1:]

  regepoch=int(reg[reg.find('"')+1:reg.find(">")-1])

  return playcount,regformatted,regepoch


def getPlayCounts(username):
  playcount,regformatted,regepoch=getUserInfo(username)

  now=time.time()
  membertime=now-regepoch

  perday   = playcount/(membertime/60/60/24)
  perweek  = perday*(365.25/52.177)
  permonth = perday*(365.25/12)
  peryear  = perday*(365.25)

  return regformatted,perday,perweek,permonth,peryear,membertime/60/60/24


registered,perday,perweek,permonth,peryear,totdays=getPlayCounts(username)

font=ImageFont.truetype(fontfile, fontsize)

lines = ['%s:' % username,
         '%s Tracks per Day'   % locale.format('%.1f', perday,   3),
         '%s Tracks per Week'  % locale.format('%.1f', perweek,  3),
         '%s Tracks per Month' % locale.format('%.1f', permonth, 3),
         '%s Tracks per Year'  % locale.format('%.1f', peryear,  3),
         'Listening Since:',
         '%s (%d days)' % (registered, totdays)]

maxwidth  = 0
linecount = 0

for line in lines:
  w,h=font.getsize(line)
  if w>maxwidth:
    maxwidth=w

h +=1 #Add spacing

img  = Image.new('RGBA', (maxwidth, h*len(lines)), bg)
draw = ImageDraw.Draw(img)
draw.fontmode = '0'

for line in lines:
  draw.text((0,h*linecount), line, font=font, fill=fg)
  linecount += 1

img.save('~/public_html/last-fm.jpg','JPEG',quality=100)