# 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 lyricscom():

    __name__ = 'Lyrics.com'
    __version__ = '0.1.1'
    __author__ = 'BadChoice <guitarboy000@gmail.com>'
    __desc__ = 'API to load Lyrics.com lyrics'
    
    URL = ""
    
    def get_data( self , artist, song ):
    
        artist_name = artist.replace(" ","-")
        artist_name = artist_name.replace("\'","")
        artist_name = urllib.quote(artist_name.encode('utf-8'))
        song_name = song.replace(" ","-")
        song_name = song_name.replace("\'","")
        song_name = urllib.quote(song_name.encode('utf-8'))
        
        self.URL = "http://lyrics.com/lyrics/" + artist_name + "/" + song_name +".html"
        c.debug('Lyrics.com URL: ' + self.URL)
        web = urllib.urlopen(self.URL)
        webcode = web.read()
        
        #the *? is non greedy so it takes just one <div
        #<div id="lyric_space"> ===> Start of the div where the song is located
        #(?:\s*?<.*?>)?                ===> Take out all the leading spaces and one <*>  (Non greedy!!!!)
        #    (?:          ==> don't count it on group
        #    \s*?         ==> leading whitespaces (Non greddy)
        #    <.*?>        ==> the <*> (Non greedy)
        #    )?           ==> one time or zero
               
        #(.*)         ===> The lyric
        #---<br />    ===> Match the end of the lyric

        regexp = re.compile ('<div id="lyric_space">(?:\s*?<.*?>)?(.*)---<br />',re.DOTALL)
        m = re.search(regexp, webcode)

        if m:
            lyric = m.group(1).replace("<br />", "")
            lyric = lyric.replace("&#xD;", "")
            lyric = lyric.strip()
            return lyric
        else:
            return None
                
    #==================== GET WEBPAGE ============================= #
    def get_webpage(self):
        return self.URL
