#!/usr/bin/python
import sys,os
import gettext
import apt
from PyQt4.QtCore import *
from PyQt4.QtGui import *

gettext.textdomain('kaffeine-install-codecs')

def _(string):
    return unicode(gettext.gettext(string), 'utf-8')

if len(sys.argv) < 2:
    sys.exit(1)

class InstallerOpProgress(apt.OpProgress):
    def __init__(self, installer):
        self.installer = installer

    def update(self, percent):
        self.installer.progress.setValue(percent)
        QApplication.processEvents()

    def done(self):
        self.installer.progress.setValue(100)
        QApplication.processEvents()

class CodecInstallerWidget(QDialog, apt.OpProgress):
    def __init__(self):
        QDialog.__init__(self)
        self.setWindowTitle(_('Kaffeine codec installer'))
        self.setModal(True)
        self.status = QLabel()
        self.status.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.progress = QProgressBar()
        layout = QVBoxLayout()
        layout.addWidget(self.status)
        layout.addWidget(self.progress)
        self.setLayout(layout)
        self.setStatus(_('Initializing...'))

        desktop = QApplication.desktop()
        self.setMinimumWidth(desktop.width() / 3)
        self.adjustSize()
        self.move((desktop.width()-self.width()) / 2,
                  (desktop.height()-self.height()) / 2)
        self.show()
        self.run()

    def setStatus(self, text):
        self.status.setText('<i>' + text + '</i>')
        QApplication.processEvents()

    def init_apt_cache(self):
        self.setStatus(_('Preparing...'))
        self.apt_cache = apt.Cache(InstallerOpProgress(self))

    def run(self):
        if sys.argv[1] == 'ffmpeg':
            self.installer = self.install_ffmpeg
        elif sys.argv[1] == 'dvdcss':
            self.installer = self.install_dvdcss
        else:
            QMessageBox.critical(self, _('Error'), _('Unknown codec type'))
            QApplication.exit(1)
            return

        if not self.installer():
            QApplication.exit(1)
            return

        os.system('dcop kaffeine KaffeineIface reloadEngine')
        os.system('dcop kaffeine KaffeineIface play')
        QApplication.exit(0)

    def check_already_installed(self, pkg):
        if pkg and pkg.isInstalled:
            QMessageBox.critical(self, _('Error'), _('Codec package is already installed'))
            QApplication.exit(1)
            return True
        return False

    def install_ffmpeg(self):
        self.init_apt_cache()
        pkg = self.search_pkg('libxine','-ffmpeg')

        if self.check_already_installed(pkg):
            return False

        confirm = QMessageBox.question(self, _('Codec not found'),
                                       _('Kaffeine does not have a codec '
                                         'installed to play this file. '
                                         'Do you want to install the codecs?'),
                                      QMessageBox.Yes | QMessageBox.No)
        if (confirm == QMessageBox.No):
            QApplication.exit(1)
            return False

        self.setStatus(_('Installing...'))
        QApplication.processEvents()
        self.install_cache_package(pkg)
        return True

    def install_cache_package(self, pkg):
        if os.system('kdesu -d \'adept_batch install ' + pkg.name + '\'') != 0:
            QApplication.exit(1)
            return

    def search_pkg(self, prefix, suffix = ''):
        for pkg in self.apt_cache:
            if pkg.name.startswith(prefix) and pkg.name.endswith(suffix):
                return pkg
        return None

    def install_dvdcss(self):
        self.init_apt_cache()
        pkg = self.search_pkg('libdvdcss')

        if self.check_already_installed(pkg):
            return False

        answer = QMessageBox.question(self, _('Codec not found'),
                                      _('LibDVDCSS (http://www.videolan.org/developers/libdvdcss.html) '
                                        'is about to be installed, it allows you to watch encrypted DVD '
                                        'videos.  This is illegal in some countries which '
                                        'require decryption to be authorised by the copyright holder. '
                                        'Do you want to install this package?'),
                                      QMessageBox.Yes | QMessageBox.No)
        if (answer == QMessageBox.No):
            QApplication.exit(1)
            return False

        self.setStatus(_('Installing...'))
        QApplication.processEvents()

        distro_arch = os.popen('dpkg --print-installation-architecture').read()
        distro_arch = distro_arch[:-1] # remove trailing newline
        libdvdcss_url = 'http://kubuntu.org/packages/libdvdcss-' + distro_arch + '.deb'
        os.system('kfmclient exec ' + libdvdcss_url)
        return True

app = QApplication(sys.argv)
window = CodecInstallerWidget()
window.exec_()

