#!/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/>.
'''
import sip
sip.setapi('QString',2) 

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.phonon import Phonon
from PyQt4.QtWebKit import *
from kids_media_player.window import Ui_MainWindow
import json
import os
from subprocess import call
from kids_media_player.musicdir import getMusicInfo

mycwd = QDesktopServices.storageLocation(QDesktopServices.HomeLocation)
mycwd = mycwd + "/.kids_media_player"
try:
    os.chdir(mycwd)
except:
    os.mkdir(mycwd)
    os.chdir(mycwd)
newend = "/music.dir"
ofile = mycwd + newend
try:
    with open(ofile): pass
except IOError:
    getMusicInfo()
    call("dlcovers", shell=True)
     
THUMBNAIL_SIZE = 128
SPACING        = 6
IMAGES_PER_ROW = 7

class MyVideoPopup(QDialog):
    simpleSig = pyqtSignal()
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        
        self.setWindowTitle("Video")
        self.setGeometry(300,150,400,400)
        self.layout = QHBoxLayout(self)
        self.setStyleSheet("background-color: rgb(0, 0, 0)")
        self.setWindowState(Qt.WindowFullScreen)
        self.setFocusPolicy(Qt.StrongFocus)
        
    def keyPressEvent(self,event):
        if event.key() == Qt.Key_Q:
            self.reject()
        if event.key() == Qt.Key_Space:
            self.simpleSig.emit()
            
class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle("Kids\' Media Player")

        self.tableWidget.setIconSize(QSize(128,128))
        self.tableWidget.setColumnCount(IMAGES_PER_ROW)
        self.tableWidget.setGridStyle(Qt.NoPen)
        
        self.listWidget.setFont(QFont("Sans Serif",12))
        
        self.audio_tablewidget()
        
        self.pushButton.clicked.connect(self.video_tablewidget)
        self.pushButton_2.clicked.connect(self.audio_tablewidget)
        
        self.webView.load(QUrl("http://code.google.com/p/kids-media-player/"))
        
        
    def audio_tablewidget(self):
        musicdir=open('music.dir')
        global musicdict
        musicdict = json.load(musicdir)
        musicdir.close()
     
        rowCount=len(musicdict.keys())//IMAGES_PER_ROW
        if len(musicdict.keys())%IMAGES_PER_ROW: rowCount+=1
        self.tableWidget.setRowCount(rowCount)
        
        global picposdict
        picposdict = {}
        vidposdict = {}
        row=-1
        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):
            col=i%IMAGES_PER_ROW
            if not col: row+=1
            pictemplist = musicdict[dictlist[i]]
            temppiclist = pictemplist[1]
            self.addPicture(row, col, temppiclist)
            pichome = str(temppiclist)
            picposdict.update({pichome : (row,col)})

        # Set the default column width and hide the header
        self.tableWidget.verticalHeader().setDefaultSectionSize(THUMBNAIL_SIZE+SPACING)
        self.tableWidget.verticalHeader().hide()
     
        # Set the default row height and hide the header
        self.tableWidget.horizontalHeader().setDefaultSectionSize(THUMBNAIL_SIZE+SPACING)
        self.tableWidget.horizontalHeader().hide()

        self.pushButton_4.setIcon(QIcon('/usr/share/kids_media_player/pics/play.png'))
        self.tableWidget.cellClicked.connect(self.videocell_clicked)   
        self.tableWidget.cellClicked.disconnect(self.videocell_clicked)   
        self.tableWidget.cellClicked.connect(self.audiocell_clicked)
        self.listWidget.itemClicked.connect(self.item_clicked)
        self.pushButton_3.clicked.connect(QApplication.quit)
        self.pushButton_4.clicked.connect(self.audio_pause)
        self.pushButton_5.clicked.connect(self.audio_stop)

    def video_tablewidget(self):
        self.listWidget.clear()
        self.tableWidget.clear()
        mycwd = os.getcwd()
        newend = "/pics/videos/"
        jpgpath = mycwd + newend
        picpath = mycwd + "/pics/"
        if os.access(picpath, os.W_OK):
            pass
        else:
            os.mkdir(picpath)
        if os.access(jpgpath, os.W_OK):
            pass
        else:
            os.mkdir(jpgpath)

        videoPath = QDesktopServices.storageLocation(QDesktopServices.MoviesLocation)
        vidlist = os.listdir(videoPath)
        for possvideo in list(vidlist):
            if possvideo.lower().endswith(('.m4v','.mov','.mpeg','.mp4')):
                ofile = jpgpath + os.path.splitext(possvideo)[0] + '.jpg'
                try:
                    with open(ofile): pass
                except IOError:
                    filetocall = "ffmpegthumbnailer " + "-i " + "'" + videoPath + "/" + possvideo + "'" " -o " + "'" + ofile + "'" + " -f" + " -a"
                    call(filetocall, shell=True)
            else:
                vidlist.remove(possvideo)
        filecount = len(vidlist)
 
        rowCount = filecount//IMAGES_PER_ROW
        if filecount %IMAGES_PER_ROW: rowCount+=1
        self.tableWidget.setRowCount(rowCount)
        
        global vidposdict
        vidposdict = {}
        picposdict = {}
        row=-1

        for i,video in enumerate(vidlist):
            videopic = jpgpath + os.path.splitext(video)[0] + '.jpg'
            video = videoPath + "/" + video
            col=i%IMAGES_PER_ROW
            if not col: row+=1
            self.addPicture(row, col, QPixmap(videopic))
            vidposdict.update({video: (row,col)})
                   
        # Set the default column width and hide the header
        self.tableWidget.verticalHeader().setDefaultSectionSize(THUMBNAIL_SIZE+SPACING)
        self.tableWidget.verticalHeader().hide()
     
        # Set the default row height and hide the header
        self.tableWidget.horizontalHeader().setDefaultSectionSize(THUMBNAIL_SIZE+SPACING)
        self.tableWidget.horizontalHeader().hide()

        self.tableWidget.cellClicked.connect(self.audiocell_clicked)
        self.tableWidget.cellClicked.disconnect(self.audiocell_clicked)
        self.tableWidget.cellClicked.connect(self.videocell_clicked)
        self.pushButton_3.clicked.connect(QApplication.quit)
        
    @pyqtSlot()
    def videocell_clicked(self):
        row = self.tableWidget.currentItem().row()
        col = self.tableWidget.currentItem().column()
        self.listWidget.clear()
            
        for tempvidhome in vidposdict.keys():
            if vidposdict[tempvidhome] == (row,col):
                try:
                    if self.mediaObject.state() == Phonon.PlayingState:
                        self.mediaObject.stop()
                except AttributeError:
                    pass
                self.media = Phonon.MediaObject(self)
                self.video = Phonon.VideoWidget(self)
                self.video.setMinimumSize(640,480)
                self.audio = Phonon.AudioOutput(Phonon.VideoCategory, self)
                Phonon.createPath(self.media, self.audio)
                Phonon.createPath(self.media, self.video)

                self.media.setCurrentSource(Phonon.MediaSource(tempvidhome))
                self.media.play()
                self.mypopup = MyVideoPopup(self)
                self.mypopup.layout.addWidget(self.video)
                self.mypopup.show()
                self.mypopup.raise_()
                self.mypopup.rejected.connect(self.mediastop)
                self.mypopup.simpleSig.connect(self.pausekey)
        
    def mediastop(self):
        self.media.stop()
        
    def pausekey(self):
        if self.media.state() == Phonon.PlayingState:
            self.media.pause()
        else:
            self.media.play()

#we have to define populate_listwidget up here before it is called by a click
    def populate_listwidget(self, musiclist2 = []):
        self.listWidget.clear()
        global musiclist
        musiclist = musiclist2
#now we are going to split the absolute path of the song
#to get the song title and then split to remove the .mp3 extension
#and loop to do that for every song in our musiclist then add to listwidget
        musiclist.sort()
        for song in musiclist: 
            head,song = os.path.split(song)
            song,songext = os.path.splitext(song)
            self.listWidget.addItem(song)
        
    @pyqtSlot()
    def audiocell_clicked(self):
        row = self.tableWidget.currentItem().row()
        col = self.tableWidget.currentItem().column()

        for temppichome in picposdict.keys():
            if picposdict[temppichome] == (row,col):
#At this point, temppichome has stored the absolute file path of the cover.jpg
#so now we break musicdict down into album, musiclist (songlist) and coverart
                for album, (musiclist, coverart) in musicdict.iteritems():
                    if str(temppichome) == str(coverart):
#if this is true, we've found the album by matching the coverart value
#                        musiclist,coverart = musicdict[album]
#so send the musiclist off to populate_listwidget 
                        self.populate_listwidget(musiclist)

    def addPicture(self, row, col, picturePath):
        item=QTableWidgetItem()
     
        # Scale the image by either height or width and then 'crop' it to the
        # desired size, this prevents distortion of the image.
        p=QPixmap(picturePath)
        if p.height()>p.width(): p=p.scaledToWidth(THUMBNAIL_SIZE)
        else: p=p.scaledToHeight(THUMBNAIL_SIZE)
        p=p.copy(0,0,THUMBNAIL_SIZE,THUMBNAIL_SIZE)
        item.setIcon(QIcon(p))
#this is how we add items to the tablewidget     
        self.tableWidget.setItem(row,col,item)
#############END TABLEWIDGET###############
    

    @pyqtSlot()
    def item_clicked(self):
        row = self.listWidget.currentRow()
        song = musiclist[row]
        self.mediaObject = Phonon.createPlayer(Phonon.MusicCategory)
        self.audioOutput = Phonon.AudioOutput(Phonon.MusicCategory, self)
        Phonon.createPath(self.mediaObject, self.audioOutput)
        self.volumeSlider.setAudioOutput(self.audioOutput)
        self.mediaObject.setCurrentSource(Phonon.MediaSource(song))
        self.mediaObject.play()
        self.pushButton_4.setIcon(QIcon('/usr/share/kids_media_player/pics/pause.png'))
        for album, (musiclist2, coverart) in musicdict.iteritems():
            if str(song) in musiclist2:
                tempvar = musicdict[album]
                path,pic = os.path.split(tempvar[1])
                newpath = path + "/browser.url"
                try:
                    with open(newpath, "r") as f:
                        newurl = f.readline()
                        newurl = str(newurl.rstrip())
                except IOError:
                    newurl = "http://www.wikipedia.org/wiki/Special:Search/" + album
                self.webView.load(QUrl(newurl))
        
    
    @pyqtSlot()
    def audio_pause(self):
        if self.mediaObject.state() == Phonon.PlayingState:
            self.mediaObject.pause()
            self.pushButton_4.setIcon(QIcon('/usr/share/kids_media_player/pics/play.png'))
        else:
            self.mediaObject.play()
            self.pushButton_4.setIcon(QIcon('/usr/share/kids_media_player/pics/pause.png'))

    @pyqtSlot()
    def audio_stop(self):
        self.mediaObject.stop()
        self.pushButton_4.setIcon(QIcon('/usr/share/kids_media_player/pics/play.png'))
            
if __name__=="__main__":
    from sys import argv, exit
     
    a=QApplication(argv)
    a.setApplicationName("Kids\' Media Player")
    m=MainWindow()
    m.show()
    m.raise_()
    exit(a.exec_())

