import sqlite3
import sys
import requests
import xml.dom.minidom
from os import path

con = None
artists = {}
url_params = {}
total_pages = -1
page_no = 0
user_name = sys.argv[1]
banshee_db = path.expanduser("~/.config/banshee-1/banshee.db")

con = sqlite3.connect(banshee_db)
cur = con.cursor()

while True:

    if total_pages == page_no:
        break

    url_params['page'] = page_no
    page_no = page_no + 1

    r = requests.get("http://ws.audioscrobbler.com/2.0/user/" + user_name + "/lovedtracks.xml",params = url_params)

    request_result = xml.dom.minidom.parseString(r.content)

    if total_pages == -1:
        total_pages = int(request_result.getElementsByTagName("lovedtracks")[0].attributes["totalPages"].value)

    for track_data in request_result.getElementsByTagName("track"):

        track_raw = track_data.getElementsByTagName("name")[0].firstChild.nodeValue
        artist_raw = track_data.getElementsByTagName("name")[1].firstChild.nodeValue

        track = track_raw.lower().replace("'","").replace(".","")
        artist = artist_raw.lower().replace("'","").replace(".","")

        print track,
        print '|',
        print artist,
        print '|',

        if artist not in artists:
            cur.execute('SELECT ca.ArtistId FROM CoreArtists ca WHERE ca.NameLowered = ? LIMIT 1',(artist,))
            row = cur.fetchone()

            if row == None:
                print 'artist not found'
                continue

            artists[artist] = row[0]

        artist_id = artists[artist]

        print artist_id,
        print '|',

        try: 
            with con:
                cur.execute('UPDATE CoreTracks SET Rating = 5 WHERE CoreTracks.TitleLowered = ? AND CoreTracks.ArtistId = ? ', (track,artist_id,))
        except sqlite3.Error, e:
            print "error %s:" % e.args[0]
            sys.exit(1)

        print 'updated' ,cur.rowcount

if con:
    con.close()

