#!/usr/bin/env python
import os,sys

class bluepin:
	DEF_PAD = 5
	EXIT_OK = False
	if os.name == "nt":
		PIN_FILENAME = ".\\pin"
	else:
		PIN_FILENAME = "/etc/bluetooth/pin"
	
	def __init__(self):
		pin = ""
		if os.path.isfile(self.PIN_FILENAME):
			f=open(self.PIN_FILENAME, "r")
			pin = f.readline()
			f.close()
			pin = pin.strip()
		if (pin != ""):
			sys.exit("PIN:"+pin);
		else:
			global gtk
			import gtk

	        # create a new window
	        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
	        self.window.set_title("Enter Bluetooth PIN")
	        self.window.set_border_width(10)
	        self.window.set_position(gtk.WIN_POS_CENTER)
	        self.window.set_resizable(gtk.FALSE)
	        self.window.connect("delete_event", self.exit_bad)
	        self.window.connect("destroy", self.exit_bad)
	        MainBox = gtk.VBox(gtk.FALSE, self.DEF_PAD)
	        self.window.add(MainBox)

		hbox = gtk.HBox(gtk.FALSE, self.DEF_PAD)
		MainBox.pack_start(hbox, gtk.FALSE, gtk.TRUE, 0)
		
	        label = gtk.Label("Bluetooth PIN:")
	        hbox.pack_start(label, gtk.FALSE, gtk.TRUE, 0)

	        self.blue_pin = gtk.Entry(0)
	        self.blue_pin.set_text("PIN")
	        self.blue_pin.set_size_request(160,30)
		hbox.pack_end(self.blue_pin, gtk.FALSE, gtk.TRUE, 0)
		
	# Ok and Cancel buttons
	        bbox = gtk.HButtonBox()
		MainBox.pack_start(bbox, gtk.FALSE, gtk.FALSE, 0)
	        bbox.set_layout(gtk.BUTTONBOX_SPREAD)
	   	
	        cancel_button = gtk.Button("Cancel",gtk.STOCK_CANCEL)
	        cancel_button.connect("clicked", self.exit_bad)
	        bbox.add(cancel_button)

	        okbutton = gtk.Button("Ok",gtk.STOCK_OK)
	        okbutton.connect("clicked", self.exit_good)
	        bbox.add(okbutton)
	        okbutton.set_flags(gtk.CAN_DEFAULT)
	        okbutton.grab_default()

	        self.window.show_all()

	def exit_bad(self,widget):
		print "ERR"
		sys.exit()
		gtk.main_quit()

	def exit_good(self,widget):
		pin = self.blue_pin.get_text()
		pin = pin.strip()
		if (pin == False or pin == ""):
			print "ERR"
		else:
			print "PIN:" + pin
		sys.exit()
		gtk.main_quit()

	def main(self):
        	gtk.main()

if __name__ == "__main__":
	bluepin = bluepin()
	bluepin.main()

