#!/usr/bin/python

import os
import sys
import fileinput
import re
import sha
import base64
import subprocess
import musicbrainz2.webservice as ws
import musicbrainz2
import logging
import glob
import urllib2

##########################################################################
## musicbrainz helper code                                              ##
##########################################################################
class MusicBrainzHelper():
	def __init__(self, host="musicbrainz.org"):
		service = ws.WebService(host)
		self.query = ws.Query(service)

	# find a set of possible matches in musicbrainz given a disk id.  This
	# returns a results array
	def findByDiscId(self, discId):
		try:
			filter = ws.ReleaseFilter(discId=discId)
			results = self.query.getReleases(filter=filter)
		except ws.RequestError:
			results = []

		# re-populate the results list with full track and artist info
		for result in results:
			result.release = self.getReleaseById(result.release.id)
			if (result.release.isSingleArtistRelease()):
				result.release.artist = self.getArtistById(result.release.artist.id)

		return results

	# find a set of possible matches in musicbrainz given an artist and 
	# title.  This returns a results array 
	def findByArtistAndTitle(self, artist, title):
		release = None

		filter = ws.ReleaseFilter(title=title, artistName=artist)
		results = self.query.getReleases(filter=filter)

		# re-populate the results list with full track and artist info
		print "Found %d results, downloading info for each: " % len(results)
		for result in results:
			print "  %s [%s]" % (
				result.release.title.encode('ascii', 'ignore'), 
				result.release.artist.name.encode('ascii', 'ignore'))
			result.release = self.getReleaseById(result.release.id)
			if (result.release.isSingleArtistRelease()):
				result.release.artist = self.getArtistById(result.release.artist.id)
		print "done"

		return results

	# musicbrainz search doesn't find the best hit even if the artist alias
	# would have made it have a score of 100.  Iterate through artists,
	# look at aliases, and see if we have a perfect hit
	#
	# returns the index of the best result given this artist and title
	def findBestResult(self, results, artist, title):
		bestResult = 0

		for resultIndex in range(0, len(results)):
			result = results[resultIndex]
			# iterate through the aliases.  it would be nice if releases had
			# aliases too
			for alias in result.release.artist.aliases:
				if alias.value == artist and result.release.title == title:
					bestResult = resultIndex

		return bestResult

	# get the full relase information for a release by it's id.  
	def getReleaseById(self, musicBrainzId):
		try:
			include = ws.ReleaseIncludes(artist=True, tracks=True, releaseEvents=True, counts=True, discs=True)
			release = self.query.getReleaseById(musicBrainzId, include)
		except ws.RequestError:
			release = None

		return release

	# get the full information about an artist given an id
	def getArtistById(self, artistId):
		#try:
		include = ws.ArtistIncludes(aliases=True, releaseRelations=False, releases=(), vaReleases=())
		artist = self.query.getArtistById(artistId, include)
		#except:
		#	artist = None

		return artist

	# print the track information for a release to the console
	def printRelease(self, release):
		print "artist: %s" % release.artist.name
		print "title: %s" % release.title
		print "year: %s" % release.getEarliestReleaseDate()
		print "asin: %s" % release.asin
		print "id: %s" % release.id
		singleArtist = release.isSingleArtistRelease()
		if (singleArtist):
			print "compilation: false"
		else:
			print "compilation: true"
		print "tracks:"
		for trackIndex in range(0, len(release.tracks)):
			track = release.tracks[trackIndex]
			if singleArtist or track.artist == None:
				print "	 %02d -- %s" % (trackIndex + 1, track.title)
			else:
				print "	 %02d -- %s [%s]" % (trackIndex + 1, track.title, track.artist.name)

