"""
MusicBrainz parser.
"""

import sys, os
import string, re
import StringIO

import htmllib, formatter
import strxtra

from arubomu.parsers.base import Fetcher
from arubomu.album import Song, Musician, Album, Disc

# musicbrainz imports
from musicbrainz2.webservice import Query, TrackFilter, WebServiceError, ReleaseIncludes


__all__ = ['MusicbrainzFetcher']


def create_fetcher():
    return MusicbrainzFetcher()


class MusicbrainzFetcher(Fetcher):

    url = 'http://musicbrainz.org/release/%s.html'

    def geturl(self, catalog_number):
        return catalog_number

    def fetch(self, url):
        releaseid = url

        q = Query()
        i = ReleaseIncludes(
            artist=True,
            tracks=True,
            urlRelations=True,
            #labels=True,
            )
        rel = q.getReleaseById(releaseid, i)

        write = lambda x: sys.stdout.write(x + '\n')

        a = Album()
        a.title = rel.title
        a.artist = rel.artist.name
        a.reldate = rel.getEarliestReleaseDate()
        if not a.reldate:
            a.reldate = ''
        ev = rel.getEarliestReleaseEvent()
        if ev is not None:
            label = ev.getLabel()
            if label:
                a.label = label.getName()
        a.catalogs.append( ('musicbrainz', releaseid) )
        a.catalogs.append( ('amazon', rel.getAsin()) )

        disc = Disc()
        disc.no = 1
        disc.songs = titles = {}
        for no, trk in enumerate(rel.tracks):
            no += 1
            s = Song(no)
            s.title = trk.title
            s.artist = trk.artist.name if trk.artist else None
            titles[no] = s
        a.discs[1] = disc

        return a, None
        

