#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 
# wup? - This simple script fetches all events from Last.fm from given location.
# 
# @author:     starenka
# @email:      admin[at]starenka[dot]net
# @version:    0.1.1
# @since       2009-05-13
# @depends     pyxml
#
import sys,urllib2,urllib
from xml.dom.ext.reader import Sax2
from xml.dom.NodeFilter import NodeFilter
from optparse import OptionParser

RESET = "\033[m"
B = "\033[1m"
U = "\033[4m"
BASE = 'http://ws.audioscrobbler.com/2.0/?method=geo.getevents&location='
API_KEY = 'b01ba280b58cf905d43dd987066fa113'
events = []

def parse_xml(exml):
    global events

    reader = Sax2.Reader()
    doc = reader.fromStream(exml)

    walker = doc.createTreeWalker(doc.documentElement,NodeFilter.SHOW_ELEMENT,None, 0)
    while 1:
        event = {'title':'','artists':[],'headliner':'','venue':'','start':''}
        if walker.currentNode.tagName == 'event':
            for node in walker.currentNode.childNodes:
                #no text nodes, pls
                if node.nodeType == 1: 
                     if node.tagName == 'startDate':
                        event['start'] = node.firstChild.nodeValue  
                     if node.tagName == 'artists':
                         for anode in node.childNodes:
                             if anode.nodeType == 1 and anode.tagName == 'headliner':
                                 event['headliner'] = anode.firstChild.nodeValue
                             if anode.nodeType == 1 and anode.tagName == 'artist':
                                 event['artists'].append(anode.firstChild.nodeValue)
                     if node.tagName == 'title':  
                        event['title'] = node.firstChild.nodeValue
                     if node.tagName == 'venue':
                         for vnode in node.childNodes:
                             if vnode.nodeType == 1 and vnode.tagName == 'name':
                                 event['venue'] = vnode.firstChild.nodeValue
                             if vnode.nodeType == 1 and vnode.tagName == 'location':
                                 for lnode in vnode.childNodes:
                                     if lnode.nodeType == 1 and lnode.tagName == 'city':
                                         try: event['venue'] += ' ('+lnode.firstChild.nodeValue+')'
                                         except: pass                            
            events.append(event)
        next = walker.nextNode()
        if next is None: break

usage = """usage:\twup -l location [-p pages]
\twup -l Prague 10
\twup -l 'New York' 15"""
parser = OptionParser(usage)
parser.add_option('-l','--location',action='store',dest='location',default=None,\
                  help='sets location (f.e Prague,London,\'New York\')')
parser.add_option('-p','--pages',action='store',dest='pages',default = 10,\
                  help='number of pages to fetch from Last.fm API')
(options,args) = parser.parse_args()    

if options.location == None:
    print 'Missing location\n'+usage
    sys.exit()

for p in range(1,int(options.pages)+1):
    try:
        print 'Fetching events (page #'+str(p)+'/'+str(options.pages)+')...'
        parse_xml(BASE+urllib.quote(options.location)+'&api_key='+API_KEY+'&page='+str(p))
    except urllib2.HTTPError, e:
        print 'Ooops. An error occured... '+str(e.code)
    except urllib2.URLError, e:
        print 'Ooops. An error occured... '+str(e)    

date = ''
for e in events:
    if e['start'] != date: 
        date = e['start']
        print '\n'+U+e['start']+RESET
    buff= '\t'+e['venue']
    buff+= u' ⚑ '+e['title']+u' ⚑ '
    if e['headliner'] in e['artists']: e['artists'].remove(e['headliner'])
    buff+= u' ♫ '+B+e['headliner']+RESET
    for a in e['artists']: buff += ', '+a
    buff+=u' ♫'
    print buff