from prismriver.plugin.common import Plugin
from prismriver.struct import Song


class UtaNetPlugin(Plugin):
    ID = 'utanet'
    RANK = 9

    def __init__(self, config):
        super(UtaNetPlugin, self).__init__('Uta-Net', config)

    def search_song(self, artist, title):
        link = 'http://www.uta-net.com/search/?Aselect=2&Keyword={}'.format(
                self.prepare_url_parameter(title, delimiter='+'))

        page = self.download_webpage(link)

        if page:
            soup = self.prepare_soup(page)

            search_pane = soup.find('tbody')
            for item in search_pane.findAll('tr', recursive=False):
                tds = item.findAll('td', recursive=False)

                song_artist = tds[1].a.text
                song_title = tds[0].a.text
                song_id = tds[0].a['href'].split('/')[2]

                if self.compare_strings(artist, song_artist) and self.compare_strings(title, song_title):
                    song_link = 'http://www.uta-net.com/user/phplib/svg/showkasi.php?ID={}'.format(song_id)
                    song_xml = self.download_xml(song_link)
                    if song_xml:
                        lyric_pane = song_xml.find('g')

                        lyric = ''
                        for tag in lyric_pane.iter('text'):
                            if tag.text:
                                lyric += (tag.text + '\n')
                            else:
                                lyric += '\n'

                        return Song(song_artist, song_title, self.sanitize_lyrics([lyric]))

@@ -283,32 +283,33 @@
     link = 'http
+s
 ://www.uta-net.c
@@ -349,20 +349,16 @@
 format(%0A
-    
         
@@ -977,16 +977,17 @@
  = 'http
+s
 ://www.u
@@ -1001,42 +1001,16 @@
 com/
-user/phplib/svg/showkasi.php?ID=
+song/
 %7B%7D
+/
 '.fo
@@ -1048,19 +1048,20 @@
    song_
-xml
+page
  = self.
@@ -1069,19 +1069,28 @@
 ownload_
-xml
+webpage_text
 (song_li
@@ -1121,19 +1121,20 @@
 if song_
-xml
+page
 :%0A      
@@ -1155,140 +1155,121 @@
     
-lyric_pane = song_xml.find('g')%0A%0A                        lyric = ''%0A                        for tag in lyric_pane.iter('text'):%0A    
+soup = self.prepare_soup(song_page)%0A                        lyric_pane = soup.find('div', %7B'id': 'kashi_area'%7D)%0A%0A
     
@@ -1295,22 +1295,20 @@
  if 
-tag.text:%0A    
+lyric_pane:%0A
     
@@ -1341,110 +1341,49 @@
 ric 
-+
 = 
-(tag.text + '%5Cn')%0A                            else:%0A                                lyric += '%5Cn'%0A%0A
+self.parse_verse_block(lyric_pane)%0A    
     

update lyrics page parser