from Tkinter import *
from listbox import *
from rhtkinter import *
from buttonbar import *
from rhutil import *
import os
import string

devices = [ ( "<none>", "No Modem"),
	    ( "cua0", "COM1: under MS-DOS"),
	    ( "cua1", "COM2: under MS-DOS"),
	    ( "cua2", "COM3: under MS-DOS"),
	    ( "cua3", "COM4: under MS-DOS") ]

class ModemWin(RHFrame):

    def createWidgets(self, standalone):
	self.message = Message(self, { 'aspect' : '450', 'text' : 
            "Select the device " + 
	    "(serial port) to which your modem is connected. If you have no " +
	    "modem, select <none>. (This configuration step simply makes a " +
            "link from /dev/modem to your actual modem device.)" } )
	self.message.pack()

	if (os.path.exists(self.root + "/dev/modem") and
	    os.path.islink(self.root + "/dev/modem")):
	    current = os.readlink(self.root + "/dev/modem")
	else:
	    current = '<none>'

	self.list = MultifieldListbox(self,
			[ ( 'Device', 10, 0 ), ( 'Information', 20, 0 ) ] )
	self.list.bind('<Double-1>', self.done)
	line = 0
	for tuple in devices:
	    self.list.insert(tuple)
	    (device, info) = tuple
	    if (device == current):
		self.list.selectLine(line)
	    line = line + 1

	self.list.pack({ 'expand' : '1', 'fill' : 'both' })

	self.Buttons = ButtonBar(self)
	self.Buttons.addButton("Ok", self.done, 1)

	if (standalone):
	    self.Buttons.addButton("Cancel", self.quit, 1)

	self.Buttons.pack({ 'fill' : 'x' })
	self.pack({ 'expand' : '1', 'fill' : 'both' })

    def done(self, e = None):
	selection = self.list.curselection()
	if (not len(selection)):
	    return
	(selection, ) = selection
	(device, comment)= devices[string.atoi(selection)]

	if (os.path.exists(self.root + "/dev/modem")):
	    if (self.test):
		print "unlinking current modem link"
	    else:
		os.unlink(self.root + "/dev/modem")

	if (device == '<none>'):
	    if (self.test):
		print "no modem link will be made"
	else:
	    if (self.test):
		print "making link from", device, "to modem"
	    else:
		os.symlink(device, self.root + "/dev/modem")

	self.quit()

    def __init__(self, test, root, standalone, Master = None):
	RHFrame.__init__(self, Master)
	self.test = test
	self.root = root
	self.createWidgets(standalone)
	if (Master):
	    Master.title("Configure Modem")

def setupmodem(test, root = "/", standalone = 0):
    win = ModemWin(test, root, standalone, Toplevel())
    win.update()
    win.wait_window(win)

