# 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
import string
import common
from common import c


class lyricswikia():
    __name__ = 'lyricswikia'
    __version__ = '0.1.2'
    __author__ = 'BadChoice <guitarboy000@gmail.com>'
    __desc__ = 'API to load WikiLyrics.com lyrics'
    
    URL = ""

    def get_data( self , artist, song ):
        artist_name = artist.replace('.','. ')
        artist_name = string.capwords(artist_name)
        artist_name = artist_name.replace('. ','.')
        artist_name = artist_name.replace(" ","_")
        artist_name = artist_name.replace("\'","")
        artist_name = urllib.quote(artist_name.encode('utf-8'))
        song_name = string.capwords(song)
        song_name = song_name.replace(" ","_")
        song_name = song_name.replace("\'","")
        song_name = urllib.quote(song_name.encode('utf-8'))
           
        self.URL = "http://lyrics.wikia.com/" + artist_name + ":" + song_name
        c.debug('lyric.wikia URL: ' + self.URL)
        web = urllib.urlopen(self.URL)
        webcode = web.read()
        
        #print webcode
        #<div class='lyricbox'>                        ==> Lyric start
        #(.*)                                        ==> Lyric itself with some divs
        #(?:<!--(.*?)<p>)                        ==> End of the lyric
        
        regexp = re.compile ("<div\s+class='lyricbox'>(.*)(?:<!--.*?<p>)",re.DOTALL)
        m = regexp.search(webcode)
        
        if m:
            lyric = m.group(1).replace("<br />", "\n")
            #(?:<div.*>)                 ==> Leading divs
            #(.*)                        ==> Finally the lyric
            regexp = re.compile ("(?:<div.*>)(.*)",re.DOTALL)
            m = re.search(regexp, lyric)
            if m:
                lyric =  m.group(1)

            lyric = common.html_unescape(lyric)
            lyric = re.sub('</?.+?>', '', lyric)
            return lyric
        else:
            #return "       No Lyric Found \n\nAnyway, You can fill it going to the webpage \n\n"
            return None

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