#!/usr/bin/env python
#
#
#    This file is part of DvdRip Queue
#    
#    DvdRip Queue 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.
#    
#    DvdRip Queue 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 DvdRip Queue.  If not, see <http://www.gnu.org/licenses/>.
#    

import os
from threading import Thread
from subprocess import Popen
from time import time, sleep
from signal import SIGTERM
import gtk
import gtk.glade

from guiFunctions import changeStockButtonText
from dvdrip_lib import getPref


class doEncode(Thread):
    """
    This is the class we use to call DvdRip... it calls it on a seperate
    thread so that the main application doesn't hang (at least that's
    what I think I've done here)
    """
    def __init__(self, ripQueue, app):
        """
        This is the class we use to call DvdRip... it calls it on a seperate thread so that the main application doesn't hang (at least that's what I think I've done here)
        """
        Thread.__init__(self)
        self.ripQueue = ripQueue
        self.cancelEncode = False
        self.app = app
        
    def run(self):
        """
        This is the function that is automatically called by Thread. It's not generally a good idea to call it manually.
        
        This function is where dvdrip is actually called using a pipe. Someday I'll see about importing dvdrip itself in order to have more control (if it's even possible).
        """
        progressDenominator = len(self.ripQueue) * 1.0
        progressNumerator = 0
        
        i=1
        for command in self.ripQueue:
            # Update the main app's progressbar
            self.updateProgressBar(progressNumerator/progressDenominator, command[1], str(command[2]))
            
            startTime = time()
            #get maxEncodeTime and convert it from minutes to seconds
            maxEncodeTime = float(getPref("maxencodetime")) * 60
            
            x = Popen(command[0].split())
            
            while (self.cancelEncode == False) and (x.poll() == None) and ((time() - startTime) < maxEncodeTime):
                gtk.gdk.threads_enter()
                gtk.gdk.threads_leave()
                sleep(0.5)
                
                # Prints time since project was started
                print (time() - startTime)
                
            if (self.cancelEncode == True) or ((time() - startTime) >= maxEncodeTime):
                os.kill(x.pid, SIGTERM)
                progressNumerator = 0
                break
                
            # os.kill (x.pid, SIGTERM)
            # x = Popen(["dvdrip", "-f", "transcode", "/home/jim/dvdrip-data/2-HardBoiled.rip"])
            # x.wait()       # ...then I manually close the application by cancelling the job and clicking the 'x'
            
            # Mark the progress as 1 more completed
            progressNumerator = progressNumerator + 1
            i=i+1    
                
        # Mark the progress as 1 more completed
        self.updateProgressBar(progressNumerator/progressDenominator, "", "")
        
        # Now that encoding is done... Pop up a little dialog to let
        # the user know, adn then reset the main interface
        
        self.encodeCompleteDialog = encodeCompleteDialog(self.app)
        
        self.app.nowEncoding = False
                
        self.app.addProjectButton.set_sensitive(True)
        self.app.configButton.set_sensitive(True)
        self.app.deleteSelectedButton.set_sensitive(True)
        self.app.deleteAllButton.set_sensitive(True)
        self.app.lView.set_sensitive(True)
        self.app.rView.set_sensitive(True)
         
        self.app.startEncodingButton = changeStockButtonText(self.app.startEncodingButton, "Start Encoding", "gtk-yes")
        
    def updateProgressBar(self, progress, currentFile, currentTitle):
        """
        Update the progress bar in the main application
        """
        gtk.gdk.threads_enter()
        self.app.progressBar.set_fraction(progress)
        
        # Format percentComplete as 5 digits max, with 2 as decimals
        #ex 127.24 or 1.74 this lets us get to 100 percent
        percentComplete = "%5.2f" % (progress * 100)
        fileinfo=""
        if currentFile != "":
            fileinfo = " (" + currentFile + " - Title #" + currentTitle + ")"
        self.app.progressBar.set_text(percentComplete + "% Complete" + fileinfo)
        gtk.gdk.threads_leave()
        
    def cancel(self):
        self.cancelEncode = True
        
class encodeCompleteDialog:
    def __init__(self, app):
        # Set Glade File  
        self.gladefile = "./gui/dvdrip-queue-encodeComplete.glade"
        self.wTree = gtk.glade.XML(self.gladefile) 
 
        # Get the Main window and connect the "destroy" event
        self.Window = self.wTree.get_widget("encodeCompleteWindow")
        
        # Define which function gets called for each signal (from the gui)
        dic = {    "on_okButton_clicked" : self.okClicked
              }
        
        self.wTree.signal_autoconnect(dic)
        
        if (app.encoder.cancelEncode == True):
            self.wTree.get_widget("shortText").set_label("DVD Encoding was Cancelled")
        
        self.Window.show()
        
        self.app = app
        
    def okClicked(self, widget):
        # change the progress bar back to 0% and disabled
        self.app.progressBar.set_fraction(0.0)
        self.app.progressBar.set_text("")
        
        # close this dialog
        self.Window.hide()
        self.Window.destroy()