#!/usr/bin/python
import urllib
import re
import os
from common import c

# ==================== FETCH COVER FROM AMAZON.COM ============================== #
def amazon_download_cover(artist, album, g):
	# make the vars lower
	try:
		artist = artist.lower()
		album = album.lower()
	except:
		return ""

	# first check if we already have the cover
	filepath = "~/.covers/"+artist+"-"+album+".jpg"
	filepath = filepath.replace(" ","_")
	filepath = os.path.expanduser(filepath)
	
	if os.path.isfile(filepath):
		g.debug("Coverfile already exists!")
		return filepath
	
	if artist == None:
		g.warning("No Artist")
	else:
		artist = urllib.quote(artist.encode('utf-8'))
	if album == None:
		g.warning("No Album")
	else:
		album = urllib.quote(album.encode('utf-8'))

	#g.debug("Downloading Cover for " + artist + " - " + album)
	# check connection
	checkurl = "http://www.google.com/robots.txt"
	try:
		connection = urllib.urlopen(checkurl)
		# succesfull, close connection
		connection.close()
	except:
		# no internets!!! go return nothing
		g.warning("No internet connection!")
		return ""
	
	# check for ~/.covers
	d = os.path.dirname(os.path.expanduser("~") + "/.covers/something.XXX")
	g.debug("Path for Amazon covers: " + d)
	if not os.path.exists(d):
		g.debug("no .covers dir so creating it")
		os.makedirs(d)

	# strip the vars from spaces
	artist = artist.replace(" ", "+")
	album = album.replace(" ", "+")
	
	# cover is not yet downloaded!
	URL = "http://www.albumart.org/index.php?srchkey="+artist+"+"+album+"&searchindex=Music"
	
	web = urllib.urlopen(URL)
	webcode = web.read()
	
	regex = re.compile("<img src=\"(.*)\" border=\"0\" class=\"image_border\"")
	
	# find the url we need
	try:
		search = re.search(regex, webcode)
		path = search.group(1)
		g.debug("Image url: "+path)
	except:
		g.warning("Cover not found")
		return ""
	
	# actually download it
	try:
		urllib.urlretrieve(path, filepath)
	except:
		return ""
	
	# return the path nice and sweet
	return filepath

# ==================== GET ALBUM FROM WIKILYRICS ============================== #
def wikiLyrics_get_album ( artist, title ):

        artist = artist.replace(" ","_")
        title = title.replace(" ","_")
        URL = "http://lyrics.wikia.com/" + artist + ":" + title
        print "Getting Album: " + URL
        web = urllib.urlopen(URL)

        try:
                webcode = web.read()

                #        appears on the album         //First string
                #        (.*?)                        //Match the title the first time (the ? adds a nongreedy search)
                #        \(.*/>                        //What is afeter the title (its non-greedy so it will return the first one)

                regexp = re.compile ("appears on the album (.*?)\(.*/>",re.DOTALL)
                m = re.search(regexp, webcode)
                return m.group(1)
        except:
                return ""

