# Copyright (C) 2009-2010 Gloobus Developers
#
#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 2
#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, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

import urllib
import re
from common import c


class absolutelyrics():

    __name__ = 'AbsoluteLyrics'
    __version__ = '0.1.1'
    __author__ = 'BadChoice <guitarboy000@gmail.com>'
    __desc__ = 'API to load AbsoluteLyrics.com lyrics'

    URL = ''
    
    def get_data(self, artsit, song):
        return self.get_lyrics(artist, song)
    
    def get_data( self , artist, song ):
        artist_name = artist.replace(" ","_")
        artist_name = urllib.quote(artist_name.encode('utf-8'))
        song_name = song.replace(" ","_")
        song_name = urllib.quote(song_name.encode('utf-8'))
        self.URL = "http://absolutelyrics.com/lyrics/view/" + artist_name + "/" + song_name +"/"
        c.debug('AbsoluteLyrics URL: ' + self.URL)
        web = urllib.urlopen(self.URL)
        web_code = web.read()
        
        #print web_code
        
        regexp = re.compile ('<div id="realText">(.*)</p></div>',re.DOTALL)
        m = re.search(regexp, web_code)
        
        #print "===================================\n\n\n"
        #print m
        
        if m:        
            lyric = m.group(1).replace("<br />", "\n")
            lyric = re.sub('</p>\s?<p.+?>','\n\n', lyric)
            #print lyric        
            self.song = unicode.encode(song) +"\n" + unicode.encode(artist) + "\n\n" + lyric
            lyric = re.sub('</?.+?>', '', lyric)
            return lyric
        else:
            return None

    #==================== GET WEBPAGE ============================= #
    def get_webpage(self):
        return self.URL
