#!/usr/bin/python
'''COPYRIGHT NOTICE
THIS PROGRAM IS COPYRIGHT 2013 MICHAEL STAGGS
THE COPYRIGHT HOLDER CAN BE REACHED AT TAUSCIAM@GMAIL.COM

    This file is part of Kids' Media Player.

    Kids' Media Player 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 3 of the License, or
    (at your option) any later version.

    Kids' Media Player 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 Kids' Media Player.  If not, see <http://www.gnu.org/licenses/>.
'''
# Many thanks go to James Stewart - the author of coverlovin https://launchpad.net/coverlovin. 
# Coverlovin is buggy and apparently no longer maintained, but it acted as a starting point for this script.

import sip
sip.setapi('QString',2) 

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import glob
import kids_media_player.id3reader
import json
import os, sys
import urllib2

#class PopBox(QDialog):
#    def __init__(self, parent=None):
#        super(PopBox, self).__init__(parent)
        

        
#        self.getCovers.getCoverImages(self)
        
class getCovers(QWidget):
    def __init__(self,parent=None):
        super(getCovers, self).__init__(parent)
        
        self.setWindowTitle('Kids Media Player - Download Covers')
        self.setMinimumSize(800,400)
        self.button = QPushButton('Ok',self)
        self.button.clicked.connect(self.destroy)
        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(self.button)
        hbox.addStretch(1)
        vbox = QVBoxLayout()
        self.lst = QListWidget(self)
        self.lst.setMinimumSize(800,300)
        vbox.addWidget(self.lst)
        vbox.addLayout(hbox)
        self.setLayout(vbox)
        
        self.msgBox = QMessageBox()
        self.msgBox.setText('Press OK to attempt to download cover art from Google. This may take several minutes')
        ret = self.msgBox.exec_()
        self.getCoverImages()

#class MainWindow(QMainWindow):
#    def __init__(self, parent=None):
#        super(MainWindow, self).__init__(parent)
#        self.setMinimumSize(600,400)
#        self.getCoverImages()
        
    def getCoverImages(self):
    
        mycwd = QDesktopServices.storageLocation(QDesktopServices.HomeLocation)
        mycwd = mycwd + "/.kids_media_player"
        try:
            os.chdir(mycwd)
        except:
            os.mkdir(mycwd)
            os.chdir(mycwd)
    
        musicdir=open('music.dir')
        musicdict = json.load(musicdir)
        musicdir.close()
    
        dictlist = list(musicdict.keys())
#we make a list of all the keys in our music dict 
#Enumerate makes it so you have a count along with each key... so you will have
#1,dictlist[1] 2,dictlist[2], etc. 
#making sure that when we hit our images per row, we add a column and keep going
#pictemplist now uses the album key to get the songlist and coverart
#and we store the coverart in temppiclist. The songlist is pictemplist[0]
        for i,picture in enumerate(dictlist):
            pictemplist = musicdict[dictlist[i]]
            temppiclist = pictemplist[1]
            for song in pictemplist[0]:
                path,song2 = os.path.split(song)
                id3r = kids_media_player.id3reader.Reader(song)
                artist = id3r.getValue('performer')
                album = id3r.getValue('album')
                if album == None:
                    temp,album = os.path.split(path)
                if artist == None:
                    temp2,artist = os.path.split(temp)

            if temppiclist == "":
                try:
                    albumwords = album.split(' ')
                except:
                    albumwords = album
                if len(albumwords) >= 2:
                    album = ""
                    for word in albumwords:
                        album += word + "+"
                    if album.endswith('+'):
                        album = album[:-1]
                artistwords = artist.split(' ')
                if len(artistwords) >= 2:
                    artist = ""
                    for word in artistwords:
                        artist += word + "+"
                    if artist.endswith('+'):
                        artist = artist[:-1]
                urlprefix = 'https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q='
                urlsuffix = '&as_filetype=jpg&imgsz=medium&rsz=8'
                request = urlprefix + artist + '+' + album + urlsuffix
                response = urllib2.urlopen(request, None, 10)
                results = json.load(response)
                urlOk = True

                try:
                    for result in results['responseData']['results']:
                        try:
                            coverImgWeb = urllib2.urlopen(result['url'], None, 10)
                        except Exception, err:
                            urlOk = False
                except:
                    self.lst.addItem('Google download error. Please try again later')
                    
                    if urlOk:
                        newcover = path + '/cover.jpg'
                        coverImgLocal = open(newcover, 'w')
                        coverImgLocal.write(coverImgWeb.read())
                        coverImgWeb.close()
                        coverImgLocal.close()
                        musicdict[dictlist[i]] = (glob.glob(path + '/*.mp3'),newcover)
                        break
                if not urlOk:
                    self.lst.addItem('Could not download cover for artist: %s album: %s' % (artist,album))

if __name__=="__main__":
     
    a=QApplication(sys.argv)
    m=getCovers()
    m.show()
    m.raise_()
    exit(a.exec_())