#!/usr/bin/python
"""
This file is part of jam-control.

jam-control 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.

fedora-audio-control 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 jam-control.  If not, see <http://www.gnu.org/licenses/>.
"""

MODULE_DIR="/usr/share/jam-control"

import sys,os

from PyQt4 import QtGui, QtCore


from subprocess import *

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s
      
sys.path.insert(0, MODULE_DIR)
from main_ui import Ui_MainWindow    
import util  
    
   
def printHelp():
    print "--start-pulse \t start Pulseaudio"
    print "--stop-pulse \t stop Pulesaudio"
    print "--start-jack \t start Jack"
    print "--stop-jack \t stop Jack"
    print "--studio-mode \t stops Pulseaudio and starts jack"
    print "--desktop-mode \t starts Pulseaudio and stops jack"


        

class MainWindow(QtGui.QMainWindow):
    """
    The app actually check to see what is installed, and that way it can work with only
    one sound server installed. Bridging will of course not be an option then
    """
    
    def __init__(self):
        super(MainWindow,self).__init__()
        
        

     
        if util.hasPulse():
            from pulseController import PulseController
            self.pulseController = PulseController()
            
        if util.hasJackDbus():
            from jackDbusController import JackDbusController
            self.jackController = JackDbusController()
        elif util.hasJack():
            from jackController import JackController
            self.jackController = JackController()
            
            
        self.timer = QtCore.QTimer(self)
        self.timer.setInterval(500)
        self.timer.timeout.connect(self.updateStatus)
        
        
       
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.show()
        self.setupSignals()
        self.initUI()
    
    def setupSignals(self):
       
        self.ui.pulseaudioBtn.clicked.connect(self.togglePulse)
        self.ui.jackBtn.clicked.connect(self.toggleJack)
        self.ui.bridgingBtn.clicked.connect(self.toggleBridge)

    
    def initUI(self):
        """
        Check the status of jack/pulse and sets the buttons and text appropiatly
        (note: will make defines for the colours to make it easier to read)
        """
        
        if self.jackController:
            if self.jackController.getStatus():
                self.ui.jackBtn.setText("Turn off \nJACK")
                self.ui.jackLbl.setStyleSheet(_fromUtf8("color: rgb(50, 205, 50);"))
            else:
                self.ui.jackBtn.setText("Turn on \nJACK")
                self.ui.jackLbl.setStyleSheet(_fromUtf8("color: rgb(255, 0, 0);"))
                
        else: 
            self.ui.jackLbl.setText("JACK is not \nInstalled")
            self.ui.jackBtn.setEnabled(False)
            self.ui.jackBtn.setText("N/A")
            self.ui.bridgingBtn.setEnabled(False)
            self.ui.jackLbl.setStyleSheet(_fromUtf8("color: rgb(255, 0, 0);"))
        if self.pulseController:
        
            if self.pulseController.getStatus():
                self.ui.pulseaudioBtn.setText("Turn off \npulseaudio")
                self.ui.pulseaudioLbl.setStyleSheet(_fromUtf8("color: rgb(50, 205, 50);"))
            else:
                self.ui.pulseaudioLbl.setStyleSheet(_fromUtf8("color: rgb(255, 0, 0);"))
                self.ui.pulseaudioBtn.setText("Turn on \npulseaudio")
        else:
            self.ui.pulseaudioLbl.setText("pulseaudio is \nnot installed")
            self.ui.pulseaudioLbl.setStyleSheet(_fromUtf8("color: rgb(255, 0, 0);"))
            self.ui.pulseaudioBtn.setText("N/A")
            self.ui.pulseaudioBtn.setEnables(False)
        self.updateBridgeButton()

        self.timer.start()

    def toggleJack(self):
        #this class should contain more error handling. It's almost a getter/setter in purpose
        if self.jackController.getStatus():
            self.jackController.stopJack()           
        else:
            self.jackController.startJack()               
        self.updateStatus()
    
    def togglePulse(self):
        #this class should contain more error handling. It's almost a getter/setter in purpose
        if self.pulseController.getStatus():            
            self.pulseController.stopPulse()            
        else:
            self.pulseController.startPulse()            
        self.updateStatus()
        
    def updateBridgeButton(self):
        """
        Checks to see if both jack AND pulse are running. If not, the bridge
        button should not be enbaled
        """
        
        if self.jackController.getStatus() and self.pulseController.getStatus():
            self.ui.bridgingBtn.setEnabled(True)
            if self.getBridgeStatus():
                self.ui.bridgingBtn.setText("Turn off \npulse/jack bridge")
            else:
                self.ui.bridgingBtn.setText("Turn on \npulse/jack bridge")
        else:
            self.ui.bridgingBtn.setEnabled(False)
            
        
    def toggleBridge(self):
        if self.getBridgeStatus():                        
            sinkid = "$(pactl list | grep -B 1 \"Name: module-jack-source\" | grep Module | sed \'s/[^0-9]//g')"
            sourceid = "$(pactl list | grep -B 1 \"Name: module-jack-sink\" | grep Module | sed \'s/[^0-9]//g')"
            check_output("pactl unload-module " + sinkid, shell=True)
            
            check_output("pactl unload-module " + sourceid, shell=True)
            self.updateBridgeButton()
        else:
            call("pactl load-module module-jack-sink channels=5", shell=True)
            call("pactl load-module module-jack-source channels=5", shell=True)
            self.updateBridgeButton()
    
    def getBridgeStatus(self):
        try: 
            check_output("pacmd list-sources| grep \"PulseAudio JACK Source\"", shell=True)
            return True
        except CalledProcessError:
            return False
        
    def updateStatus(self):
        if self.jackController.getStatus():
            self.ui.jackLbl.setStyleSheet(_fromUtf8("color: rgb(50, 205, 50);"))
            self.ui.jackBtn.setText("Turn off \nJACK")            
        else:
            self.ui.jackLbl.setStyleSheet(_fromUtf8("color: rgb(255, 0, 0);"))
            self.ui.jackBtn.setText("Turn on \nJACK")
        if self.pulseController.getStatus():
            self.ui.pulseaudioBtn.setText("Turn off \npulseaudio")
            self.ui.pulseaudioLbl.setStyleSheet(_fromUtf8("color: rgb(50, 205, 50);"))
        else: 
            self.ui.pulseaudioLbl.setStyleSheet(_fromUtf8("color: rgb(255, 0, 0);"))
            self.ui.pulseaudioBtn.setText("Turn on \npulseaudio")
        self.updateBridgeButton()

def main():
    app = QtGui.QApplication(sys.argv)
    m = MainWindow()
    m.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    """
    The commandline arguments are coming back in a later release
    """
#    controller = AudioController()
#    
#    for arg in sys.argv:
#        try:
#            if arg == "--start-pulse":             
#                controller.pulseController.startPulse()              
#            if arg == "--stop-pulse":                
#                controller.pulseController.stopPulse()                 
#            if arg == "--start-jack":              
#                controller.jackController.startJack()                     
#            if arg == "--stop-jack":          
#                controller.jackController.stopJack()
#            if arg == "--pulse-list-sources":
#                controller.pulseController.getSources()       
#            if arg == "--studio-mode":
#                controller.pulseController.stopPulse()
#                controller.jackController.startJack()
#            if arg == "--desktop--mode":
#                controller.jackController.stopJack()
#                controller.pulseController.startPulse()  
#            if arg == "--help" or arg == "-h":
#                printHelp()             
#        except AttributeError: #if the audioController does not have the required controller, it willl give an Attribute Error
#            app = arg.split("-")
#            app = app[len(app) -1]
#            print app + " is not installed"
    main()

  
