## mainWindow.py - Program creates a user interface 
##             that allows the system time, system date,
##             time zone, and ntpd configuration to be easily set
## Copyright (C) 2001, 2002, 2003 Red Hat, Inc.
## Copyright (C) 2001, 2002, 2003 Brent Fox <bfox@redhat.com>
##                          Tammy Fox <tfox@redhat.com>

## 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 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., 675 Mass Ave, Cambridge, MA 02139, USA.

import gtk
import gobject
import string
import re
import time
import os
import sys
import date_gui
import timezone_gui
import dateBackend
import timezoneBackend
import signal

##
## I18N
## 
from rhpl.translate import _, N_
import rhpl.translate as translate
translate.textdomain ("system-config-date")

#Initialize date and timezone backend
dateBackend = dateBackend.dateBackend()
timezoneBackend = timezoneBackend.timezoneBackend()
        
nameTag = _("Date & Time")
commentTag = _("Change system date and time")

class mainWindow:
    def destroy(self, args=None):
        self.win.destroy()
        gtk.mainquit()

    def response_cb (self, dialog, response_id, pid):
        if response_id == gtk.RESPONSE_CANCEL:
            os.kill (pid, signal.SIGINT)
        dialog.hide ()

    def ok_clicked(self, args):
        sysDate = self.datePage.getDate()
        sysTime = self.datePage.getTime()
        ntpEnabled = self.datePage.getNtpEnabled()

        if ntpEnabled == gtk.FALSE:
            #We're not using ntp, so stop the service
            self.dateBackend.stopNtpService()
            #set the time on the system according to what the user set it to
            self.dateBackend.writeDateConfig(sysDate, sysTime)
            self.dateBackend.syncHardwareClock()
            self.closeParent = 1
            self.dateBackend.chkconfigOff()

        elif ntpEnabled == gtk.TRUE:
            #We want to use NTP
            sysTimeServer = string.strip(self.datePage.getTimeServer())

            if sysTimeServer == "":
                self.showErrorDialog(_("Please specify an NTP server to use."))
                return

            ntpServerList = self.datePage.getNtpServerList()
            if self.dateBackend.writeNtpConfig(sysTimeServer, ntpServerList) == None:
                self.showErrorDialog(_("A connection with %s could not be established.  "
                                       "Either %s is not available or the firewall settings "
                                       "on your computer are blocking NTP connections." %
                                       (sysTimeServer, sysTimeServer)))                
                return

            def child_handler (signum, stack_frame):
                realpid, waitstat = os.waitpid(pid, os.WNOHANG)
                if realpid != pid:
                    return
                gtk.mainquit()
                result = os.read (read,100)
                os.close (read)
                signal.signal (signal.SIGCHLD, signal.SIG_DFL)
                
                if result == "" or  int(result) > 0:
                    self.showErrorDialog(_("A connection with %s could not be established.  "
                                           "Either %s is not available or the firewall settings "
                                           "on your computer are blocking NTP connections." %
                                           (sysTimeServer, sysTimeServer)))
                    return
                else:
                    self.closeParent = 1
                    gtk.mainquit()

                self.dateBackend.syncHardwareClock()

            signal.signal (signal.SIGCHLD, child_handler)
            (read, write) = os.pipe ()
            pid = os.fork ()

            if pid == 0:
                signal.signal (signal.SIGCHLD, signal.SIG_DFL)
                # do something slow
                os.close (read)
                time.sleep (2)
                retval = self.dateBackend.startNtpService(None)
                retval = str(retval)
                os.write (write, retval)
                os._exit (0)

            os.close (write)

            
            dlg = gtk.Dialog('', self.win, 0, (gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL))
            dlg.set_border_width(10)
            label = gtk.Label(_("Contacting NTP server.  Please wait..."))
            dlg.vbox.set_spacing(5)
            dlg.vbox.add(label)
            dlg.set_position (gtk.WIN_POS_CENTER_ON_PARENT)
            dlg.set_modal(gtk.TRUE)
            dlg.connect ('response', self.response_cb, pid)
            dlg.show_all()

            #work around http://bugzilla.gnome.org/show_bug.cgi?id=72333 )-;
            id = gtk.timeout_add(20, lambda:1)
            gtk.mainloop()
            dlg.destroy()
            gtk.idle_remove (id)
            
            self.dateBackend.chkconfigOn()

        #Get the timezone info from the timezone page
        timezone, utc, arc = self.timezonePage.getTimezoneInfo()
        self.timezoneBackend.writeConfig(timezone, utc, arc)

        if self.closeParent == 1:
            gtk.mainquit()

    def __init__(self, page=None):
        self.page = page
        self.dateBackend = dateBackend
        self.timezoneBackend = timezoneBackend
        self.closeParent = 0

        #--------Create main window and set attributes-------#
        self.win = gtk.Window ()
        self.win.connect ('destroy', self.destroy)
        self.win.set_title (_("Date/Time Properties"))
        self.win.set_default_size (400, 550)

        self.win.set_border_width (5)

        self.vbox = gtk.VBox (gtk.FALSE, 10)
        self.win.add (self.vbox)

        #----------------GUI-------------------#
        self.nb = gtk.Notebook()

        dateLabel = gtk.Label (_("_Date & Time"))
        dateLabel.set_use_underline(gtk.TRUE)
        timezoneLabel = gtk.Label (_("_Time Zone"))
        timezoneLabel.set_use_underline(gtk.TRUE)
        timeserverLabel = gtk.Label (_("Internet Time Servers"))

        self.vbox.pack_start(self.nb, gtk.TRUE)

        self.datePage = date_gui.datePage(self.dateBackend)
        self.datePageVBox = self.datePage.getVBox()
        
        self.nb.append_page(self.datePageVBox, dateLabel)

        self.timezonePage = timezone_gui.timezonePage()
        self.timezonePageVBox = self.timezonePage.getVBox()
        self.nb.append_page(self.timezonePageVBox, timezoneLabel)

        #----------------Buttons------------#
        lowerHBox = gtk.HBox()

        leftButtonBox = gtk.HButtonBox()
        leftButtonBox.set_layout (gtk.BUTTONBOX_START)
        helpButton = gtk.Button(stock='gtk-help')
        helpButton.connect ('clicked', self.help_clicked)        
        leftButtonBox.pack_start (helpButton)
        
        rightButtonBox = gtk.HButtonBox ()
        lowerHBox.pack_start(leftButtonBox, gtk.TRUE, 10)
        lowerHBox.pack_start(rightButtonBox, gtk.TRUE, 10)
        self.vbox.pack_start (lowerHBox, gtk.FALSE, 10)
        rightButtonBox.set_layout (gtk.BUTTONBOX_END)
        rightButtonBox.set_spacing(10)

        cancelButton = gtk.Button(stock='gtk-cancel')
        rightButtonBox.pack_start(cancelButton)
        cancelButton.connect('clicked', self.destroy)

        okButton = gtk.Button(stock='gtk-ok')
        rightButtonBox.pack_start (okButton)
        okButton.connect ('clicked', self.ok_clicked)

    def launch(self):
        if self.vbox.children() != []:
            self.vbox.remove(self.vbox.children()[0])
        else:
            pass
        return self.nb

    def help_clicked(self, args):
        help_pages = ["file:///usr/share/doc/system-config-date-1.7.3.1/time-date.html",
                      "file:///usr/share/doc/system-config-date-1.7.3.1/time-zone.html"
                      ]

        page = help_pages [self.nb.get_current_page ()]
	path = "/usr/bin/htmlview"

        if path == None:
            dlg = gtk.MessageDialog(None, 0, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK,
                                    (_("Help is not available.")))
            dlg.set_position(gtk.WIN_POS_CENTER)
            dlg.run()
            dlg.destroy()
            return
        
        pid = os.fork()
        if not pid:
            os.execv(path, [path, page])
       
    def stand_alone(self):
        self.win.show_all()
        if self.page and (self.page == 0 or self.page == 1):
            self.nb.set_current_page(self.page)
        gtk.mainloop()

    def showErrorDialog(self, text):
        dlg = gtk.MessageDialog(self.win, 0, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, text)

        dlg.set_title(_("Error"))
        dlg.set_default_size(100, 100)
        dlg.set_position (gtk.WIN_POS_CENTER_ON_PARENT)
        dlg.set_border_width(2)
        dlg.set_modal(gtk.TRUE)
        rc = dlg.run()
        dlg.destroy()
        return

class childWindow:
    runPriority = 50
    moduleName = "Date/Time"
    moduleClass = "reconfig"

    def launch(self):
        mw = mainWindow().launch()        
        return mw
