##
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program 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 Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
##

import os
import gtk
import DSApp
import DSExport
import tempfile
import platform
import Constants

class DlgPrint:
    """This class contains the implementation of the Print disk dialog
    (for the selected disk)."""

    def __init__ (self):
        """Constructor of DlgPrint class."""

        self.export = DSExport.ExportXML()
        # get the name of the selected disk
        selection = DSApp.DSApp.view.list_disks.get_selection ()
        selected_tuple = selection.get_selected ()
        selected_tree_iter = selected_tuple[1]
        if selected_tree_iter == None:
            DSApp.DSApp.view.display_message_dialog (gtk.MESSAGE_ERROR, _("You need to select a disk first!"))
            return

        # find disk and print content to buffer
        selected_disk_name = DSApp.DSApp.view.list_disks.get_model ().get_value (selected_tree_iter, 1)

        self.edited_disk = None
        for disk in DSApp.DSApp.doc.diskList.content:
            if (disk.name == selected_disk_name):
                self.edited_disk = disk
                break

        self.applications  = getApplications()
        dlg_content_widget_tree = gtk.glade.XML (Constants.RESOURCE_DIR + "/disksearch.glade", "dlg_print")
        self.dlg_edit = dlg_content_widget_tree.get_widget ("dlg_print")
        self.om_application = dlg_content_widget_tree.get_widget ("om_application")
        self.fill_optionmenu (self.om_application, self.applications)

        self.om_format = dlg_content_widget_tree.get_widget ("om_format")
        self.fill_optionmenu (self.om_format, self.export.formats)

        dlg_content_widget_tree.signal_connect ("on_cancel_clicked", self.onPrintCancel)
        dlg_content_widget_tree.signal_connect ("on_ok_clicked", self.onPrintOk)
        dlg_content_widget_tree.signal_connect ("on_bt_browse_clicked", self.onAppSelect)

        self.dlg_edit.set_transient_for (DSApp.DSApp.view.app_disksearch)
        self.dlg_edit.set_icon (DSApp.DSApp.view.pxb_appicon)
        self.dlg_edit.show ()

    def fill_optionmenu (self, option_menu, optionsDict):
        if type(optionsDict) is dict:
            optionsDict = optionsDict.values()
            optionsDict.sort()
        mTypes = gtk.Menu ()
        foundTypeIndex = 0
        for index in optionsDict:
            miType = gtk.MenuItem (index)
            miType.show ()
            mTypes.append (miType)
        option_menu.set_menu (mTypes)

    def onAppSelect(self, *args):
        chooser = gtk.FileChooserDialog(title=_("Select a browser"),action=gtk.FILE_CHOOSER_ACTION_OPEN,
                                  buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
        response = chooser.run()
        if response == gtk.RESPONSE_OK:
            self.applications = [chooser.get_filename()] + self.applications
            self.om_application.remove_menu()
            self.fill_optionmenu (self.om_application, self.applications)
            self.om_application.set_history(0)
        chooser.destroy()

    def onPrintOk(self, *args):
        formatValues = self.export.formats.values()
        formatValues.sort()
        choice = formatValues[self.om_format.get_history()]
        format = None
        for i in self.export.formats:
            if self.export.formats[i] == choice:
                format = i
                break
        app = self.applications[self.om_application.get_history()]
        filename = os.path.join(tempfile.gettempdir(), "ds_%s_%s.xml" % (self.edited_disk.timestamp, format) )
        self.export.printXML(self.edited_disk, filename, format)
        os.system("%s %s &" % (app, filename))
        self.dlg_edit.destroy ()

    def onPrintCancel(self, *args):
        self.dlg_edit.destroy ()

def getApplications():
    if platform.system() != 'Windows':
        apps = []
        for i in ['firefox', 'galeon', 'mozilla', 'opera', 'dillo', 'amaya', 'seamonkey', 'skipstone', 'swiftfox']:
            retval = os.popen("which %s" % i, 'r')
            if retval.read():
                apps.append(i)
            retval.close()
    else:
        apps = ['explorer']
    return apps
