#!/usr/bin/python
import Tkinter
import tkFileDialog
import FileDialog
import Pmw
import os
import string
import types
import os.path

def get_font():
    return "6x13"

def write_key(dict,key,fout):
    fout.write("  ")
    fout.write(key)
    fout.write("\n")
    val = "  %g\n" %(dict[key].get())
    fout.write(val)
            
class Pilot_control(Tkinter.Toplevel):
    def __init__(self):
        aframe=Tkinter.Frame()
        aframe.pack()
        Tkinter.Toplevel.__init__(self,aframe)
        self.title('Pilot configure')
        self.filename=Tkinter.StringVar()
        self.filename.set("../pilot_config.txt")

        oper_button=Tkinter.Button(self,text="Gas control",
                                   font=get_font(),
                                   command = self.call_gas)
	oper_button.pack(fill='x')

        oper_button=Tkinter.Button(self,text="Breaks control",
                                   font=get_font(),
                                   command = self.call_brk)
	oper_button.pack(fill='x')

        oper_button=Tkinter.Button(self,text="Handlebar control",
                                   font=get_font(),
                                   command = self.call_hbr)
	oper_button.pack(fill='x')

        oper_button=Tkinter.Button(self,text="Update event control",
                                   font=get_font(),
                                   command = self.call_upd)
	oper_button.pack(fill='x')

        quit_button=Tkinter.Button(self,text="Save",
                                   font=get_font(),command = self.save)
	quit_button.pack()

        quit_button=Tkinter.Button(self,text="Quit",
                                   font=get_font(),command = self.quit)
	quit_button.pack()
        
        self.init_vars()
        self.read()
        self.gas_ctrl=None
        self.brk_ctrl=None
        self.hbr_ctrl=None
        self.upd_ctrl=None
        
        self.grab_set()
        self.focus_set()
        self.wait_window()
        
    def init_vars(self):
        self.var = {}
        self.var_gas = {}
        self.gas_order=[]
        self.var_gas["thr_lateral"]=Tkinter.DoubleVar()
        self.var_gas["thr_lateral"].set(0.1)
        self.gas_order.append("thr_lateral")
        self.var_gas["thr_front"]=Tkinter.DoubleVar()
        self.var_gas["thr_front"].set(0.1)
        self.gas_order.append("thr_front")
        self.var_gas["thr_speed"]=Tkinter.DoubleVar()
        self.var_gas["thr_speed"].set(0.1)
        self.gas_order.append("thr_speed")
        self.var_gas["thr_speed_low"]=Tkinter.DoubleVar()
        self.var_gas["thr_speed_low"].set(0.1)
        self.gas_order.append("thr_speed_low")
        self.var_gas["c_inc_speed"]=Tkinter.DoubleVar()
        self.var_gas["c_inc_speed"].set(0.1)
        self.gas_order.append("c_inc_speed")
        self.var_gas["c_slope"]=Tkinter.DoubleVar()
        self.var_gas["c_slope"].set(0.1)
        self.gas_order.append("c_slope")
        self.var_gas["c_lat_speed"]=Tkinter.DoubleVar()
        self.var_gas["c_lat_speed"].set(0.1)
        self.gas_order.append("c_lat_speed")
        self.var_gas["c_fr_speed"]=Tkinter.DoubleVar()
        self.var_gas["c_fr_speed"].set(0.1)
        self.gas_order.append("c_fr_speed")
        self.var_gas["c_dec_speed"]=Tkinter.DoubleVar()
        self.var_gas["c_dec_speed"].set(0.1)
        self.gas_order.append("c_dec_speed")
        self.var_gas["c_dec_lat"]=Tkinter.DoubleVar()
        self.var_gas["c_dec_lat"].set(0.1)
        self.gas_order.append("c_dec_lat")
        self.var_gas["c_dec_fr"]=Tkinter.DoubleVar()
        self.var_gas["c_dec_fr"].set(0.1)
        self.gas_order.append("c_dec_fr")
        self.var_gas["speed_pow_lat"]=Tkinter.DoubleVar()
        self.var_gas["speed_pow_lat"].set(2)
        self.gas_order.append("speed_pow_lat")
        self.var_gas["speed_pow_fr"]=Tkinter.DoubleVar()
        self.var_gas["speed_pow_fr"].set(2)
        self.gas_order.append("speed_pow_fr")
        for x in self.var_gas.keys():
            self.var[x] = self.var_gas[x]
        
        self.var_brk = {}
        self.brk_order=[]
        self.var_brk["thr_speed"]=Tkinter.DoubleVar()
        self.var_brk["thr_speed"].set(0.1)
        self.brk_order.append("thr_speed")
        self.var_brk["thr_speed_low"]=Tkinter.DoubleVar()
        self.var_brk["thr_speed_low"].set(1)
        self.brk_order.append("thr_speed_low")
        self.var_brk["c_slope"]=Tkinter.DoubleVar()
        self.var_brk["c_slope"].set(0.1)
        self.brk_order.append("c_slope")
        self.var_brk["c_lat_speed"]=Tkinter.DoubleVar()
        self.var_brk["c_lat_speed"].set(0.1)
        self.brk_order.append("c_lat_speed")
        self.var_brk["c_fr_speed"]=Tkinter.DoubleVar()
        self.var_brk["c_fr_speed"].set(0.1)
        self.brk_order.append("c_fr_speed")
        self.var_brk["c_dec_speed"]=Tkinter.DoubleVar()
        self.var_brk["c_dec_speed"].set(0.1)
        self.brk_order.append("c_dec_speed")
        self.var_brk["c_dec_lat"]=Tkinter.DoubleVar()
        self.var_brk["c_dec_lat"].set(0.1)
        self.brk_order.append("c_dec_lat")
        self.var_brk["c_dec_fr"]=Tkinter.DoubleVar()
        self.var_brk["c_dec_fr"].set(0.1)
        self.brk_order.append("c_dec_fr")
        self.var_brk["speed_pow_lat"]=Tkinter.DoubleVar()
        self.var_brk["speed_pow_lat"].set(2)
        self.brk_order.append("speed_pow_lat")
        self.var_brk["speed_pow_fr"]=Tkinter.DoubleVar()
        self.var_brk["speed_pow_fr"].set(2)
        self.brk_order.append("speed_pow_fr")
        for x in self.var_brk.keys():
            self.var[x] = self.var_brk[x]

        self.var_hbr = {}
        self.hbr_order=[]
        self.var_hbr["thr_diff"]=Tkinter.DoubleVar()
        self.var_hbr["thr_diff"].set(0.1)
        self.hbr_order.append("thr_diff")
        self.var_hbr["thr_front"]=Tkinter.DoubleVar()
        self.var_hbr["thr_front"].set(0.1)
        self.hbr_order.append("thr_front")
        self.var_hbr["c_push"]=Tkinter.DoubleVar()
        self.var_hbr["c_push"].set(0.1)
        self.hbr_order.append("c_push")
        self.var_hbr["speed_pow"]=Tkinter.DoubleVar()
        self.var_hbr["speed_pow"].set(0.1)
        self.hbr_order.append("speed_pow")
        for x in self.var_hbr.keys():
            self.var[x] = self.var_hbr[x]
            
        self.var_upd = {}
        self.upd_order=[]
        self.var_upd["thr_lateral"]=Tkinter.DoubleVar()
        self.var_upd["thr_lateral"].set(0.5)
        self.upd_order.append("thr_lateral")
        self.var_upd["thr_front"]=Tkinter.DoubleVar()
        self.var_upd["thr_front"].set(0.1)
        self.upd_order.append("thr_front")
        self.var_upd["thr_speed_high"]=Tkinter.DoubleVar()
        self.var_upd["thr_speed_high"].set(1.2)
        self.upd_order.append("thr_speed_high")
        self.var_upd["thr_speed_low"]=Tkinter.DoubleVar()
        self.var_upd["thr_speed_low"].set(0.25)
        self.upd_order.append("thr_speed_low")
        self.var_upd["thr_safe_speed"]=Tkinter.DoubleVar()
        self.var_upd["thr_safe_speed"].set(9)
        self.upd_order.append("thr_safe_speed")
        for x in self.var_upd.keys():
            self.var[x] = self.var_upd[x]
        
    def read(self):
        try:
            input=open(self.filename.get(),"r")
        except:
            print "Could not read the preference file ", self.filename.get()
            input = None
        if input:
            line=input.readline()
            agent = "gas"
            while line:
                y=string.split(line)
                x=""
                for i in y:
                    if i:
                        x=string.split(i,'\n')[0]
                if x:
                    if not self.var.has_key(x):
                        agent = x
                    else:
                        line=input.readline()
                        y=string.split(line)
                        for i in y:
                            if i:
                                y=string.split(i,'\n')[0]
                        val=0
                        if type(self.var[x].get()) == types.IntType:
                            val=string.atoi(y)
                        elif type(self.var[x].get()) == types.FloatType:
                            val=string.atof(y)
                        else:
                            val=y
                        if agent == "gas":
                            self.var_gas[x].set(y)
                        elif agent == "breaks":
                            self.var_brk[x].set(y)
                        elif agent == "handlebar":
                            self.var_hbr[x].set(y)
                        elif agent == "update":
                            self.var_upd[x].set(y)
                line=input.readline()
            input.close()

    def save(self):
        output=open(self.filename.get(),"w")
        output.write("Agent update\n")
        for x in self.upd_order:
            write_key(self.var_upd,x,output)
        output.write("\nAgent gas\n")
        for x in self.gas_order:
            write_key(self.var_gas,x,output)
        output.write("\nAgent breaks\n")
        for x in self.brk_order:
            write_key(self.var_brk,x,output)
        output.write("\nAgent handlebar\n")
        for x in self.hbr_order:
            write_key(self.var_hbr,x,output)
        output.close()

    def call_gas(self):
        self.gas_ctrl=Gas_config(self)

    def call_brk(self):
        self.brk_ctrl=Breaks_config(self)

    def call_hbr(self):
        self.hbr_ctrl=Hbar_config(self)

    def call_upd(self):
        self.upd_ctrl=Update_config(self)

    def quit(self):
        self.save()
        self.destroy()


def makeComboBox(parent,text_str,var):
    combo_box=Pmw.ComboBox(parent,labelpos="w",label_text=text_str,
                           selectioncommand = lambda val,obj=var:obj.set(val),
                           entryfield_entry_width = 5)
    combo_box._entryWidget.config(font=get_font())
    combo_box._list.component('listbox').config(font=get_font())
    combo_box.component('label').config(font=get_font())
    combo_box.component('entryfield').setentry(var.get())
    combo_box.pack()
    return combo_box

class Gas_config(Tkinter.Toplevel):
    def __init__(self, parent=None):
        Tkinter.Toplevel.__init__(self, parent)
        self.title('Gas control')
        self.var=parent.var_gas
        self.top=parent
        pc=makeComboBox(self,"Threshold left-right safe difference",
                        self.var["thr_lateral"])
        pc.component('listbox').insert(1,0.0,0.1,0.5,1.0, 2.0)
        pc=makeComboBox(self,"Threshold front safe distance",
                        self.var["thr_front"])
        pc.component('listbox').insert(1,0.0,0.1,0.5,1.0, 2.0)
        pc=makeComboBox(self,"Threshold safe speed",
                        self.var["thr_speed"])
        pc.component('listbox').insert(1,0.0,0.1,0.5,1.0, 2.0)
        pc=makeComboBox(self,"Threshold lower speed",
                        self.var["thr_speed_low"])
        pc.component('listbox').insert(1,0.0,0.1,0.5,1.0, 2.0)
        pc=makeComboBox(self,"Constant increase gas speed",
                        self.var["c_inc_speed"])
        pc.component('listbox').insert(1,0.0,0.1,0.5,1.0, 2.0)
        pc=makeComboBox(self,"Constant increase gas slope",
                        self.var["c_slope"])
        pc.component('listbox').insert(1,0.0,0.1,0.5,1.0, 2.0)
        pc=makeComboBox(self,"Constant increase gas left-right difference",
                        self.var["c_lat_speed"])
        pc.component('listbox').insert(1,0.0,0.1,0.5,1.0, 2.0)
        pc=makeComboBox(self,"Constant increase gas front distance",
                        self.var["c_fr_speed"])
        pc.component('listbox').insert(1,0.0,0.1,0.5,1.0, 2.0)
        pc=makeComboBox(self,"Constant decrease gas speed",
                        self.var["c_dec_speed"])
        pc.component('listbox').insert(1,0.0,0.1,0.5,1.0, 2.0)
        pc=makeComboBox(self,"Constant decrease gas left-right difference",
                        self.var["c_dec_lat"])
        pc.component('listbox').insert(1,0.0,0.1,0.5,1.0, 2.0)
        pc=makeComboBox(self,"Constant decrease gas front distance",
                        self.var["c_dec_fr"])
        pc.component('listbox').insert(1,0.0,0.1,0.5,1.0, 2.0)
        pc=makeComboBox(self,"1/power speed",
                        self.var["speed_pow_lat"])
        pc.component('listbox').insert(1, 0.5, 1.0, 2.0, 3.0)
        pc=makeComboBox(self,"1/power front distance",
                        self.var["speed_pow_fr"])
        pc.component('listbox').insert(1, 0.5, 1.0, 2.0, 3.0)
        
        ok_button=Tkinter.Button(self,text="OK",font=get_font(),
                                 command = self.quit)
	ok_button.pack()

    def quit(self):
        self.top.gas_ctrl=None
        self.destroy()

class Breaks_config(Tkinter.Toplevel):
    def __init__(self, parent=None):
        Tkinter.Toplevel.__init__(self, parent)
        self.title('Breaks control')
        self.var=parent.var_brk
        self.top=parent
        pc=makeComboBox(self,"Threshold safe speed",
                        self.var["thr_speed"])
        pc.component('listbox').insert(1,0.0,0.1,0.5,1.0, 2.0)
        pc=makeComboBox(self,"Threshold speed low",
                        self.var["thr_speed_low"])
        pc.component('listbox').insert(1,0.0,0.1,0.5,1.0, 2.0)
        pc=makeComboBox(self,"Constant breaks slope",
                        self.var["c_slope"])
        pc.component('listbox').insert(1,0.0,0.1,0.5,1.0, 2.0)
        pc=makeComboBox(self,"Constant safe speed of left-right difference",
                        self.var["c_lat_speed"])
        pc.component('listbox').insert(1,0.0,0.1,0.5,1.0, 2.0)
        pc=makeComboBox(self,"Constant breaks front distance",
                        self.var["c_fr_speed"])
        pc.component('listbox').insert(1,0.0,0.1,0.5,1.0, 2.0)
        pc=makeComboBox(self,"Constant breaks speed",
                        self.var["c_dec_speed"])
        pc.component('listbox').insert(1,0.0,0.1,0.5,1.0, 2.0)
        pc=makeComboBox(self,"Constant breaks left-right difference",
                        self.var["c_dec_lat"])
        pc.component('listbox').insert(1,0.0,0.1,0.5,1.0, 2.0)
        pc=makeComboBox(self,"Constant breaks front distance",
                        self.var["c_dec_fr"])
        pc.component('listbox').insert(1,0.0,0.1,0.5,1.0, 2.0)
        pc=makeComboBox(self,"1/power speed",
                        self.var["speed_pow_lat"])
        pc.component('listbox').insert(1, 0.5, 1.0, 2.0, 3.0)
        pc=makeComboBox(self,"1/power front distance",
                        self.var["speed_pow_fr"])
        pc.component('listbox').insert(1, 0.5, 1.0, 2.0, 3.0)
        
        ok_button=Tkinter.Button(self,text="OK",font=get_font(),
                                 command = self.quit)
	ok_button.pack()

    def quit(self):
        self.top.brk_ctrl=None
        self.destroy()

class Hbar_config(Tkinter.Toplevel):
    def __init__(self, parent=None):
        Tkinter.Toplevel.__init__(self, parent)
        self.title('Handlebar control')
        self.var=parent.var_hbr
        self.top=parent
        pc=makeComboBox(self,"Threshold turn left-right difference",
                        self.var["thr_diff"])
        pc.component('listbox').insert(1,0.0,0.1,0.5,1.0, 2.0)
        pc=makeComboBox(self,"Threshold front safe distance",
                        self.var["thr_front"])
        pc=makeComboBox(self,"Constant push",
                        self.var["c_push"])
        pc.component('listbox').insert(1,0.0,0.1,0.5,1.0, 2.0)
        pc=makeComboBox(self,"1/power speed",
                        self.var["speed_pow"])
        pc.component('listbox').insert(1, 0.5, 1.0, 2.0, 3.0)
        
        ok_button=Tkinter.Button(self,text="OK",font=get_font(),
                                 command = self.quit)
	ok_button.pack()

    def quit(self):
        self.top.hbr_ctrl=None
        self.destroy()
        
class Update_config(Tkinter.Toplevel):
    def __init__(self, parent=None):
        Tkinter.Toplevel.__init__(self, parent)
        self.title('Update event control')
        self.var=parent.var_upd
        self.top=parent
        pc=makeComboBox(self,"Threshold safe left-right difference",
                        self.var["thr_lateral"])
        pc.component('listbox').insert(1,0.0,0.1,0.5,1.0, 2.0)
        pc=makeComboBox(self,"Threshold safe front distance",
                        self.var["thr_front"])
        pc.component('listbox').insert(1,0.0,0.1,0.5,1.0, 2.0)
        pc=makeComboBox(self,"High speed limit percentage",
                        self.var["thr_speed_high"])
        pc.component('listbox').insert(1,0.0,0.1,0.5,1.0, 2.0)
        pc=makeComboBox(self,"Low speed limit percentage",
                        self.var["thr_speed_low"])
        pc.component('listbox').insert(1,0.0,0.1,0.5,1.0, 2.0)
        pc=makeComboBox(self,"Threshold safe speed",
                        self.var["thr_safe_speed"])
        pc.component('listbox').insert(1, 6.0, 7.0, 8.0, 9.0)
        
        ok_button=Tkinter.Button(self,text="OK",font=get_font(),
                                 command = self.quit)
	ok_button.pack()

    def quit(self):
        self.top.upd_ctrl=None
        self.destroy()
        
if __name__ == '__main__' : 
    pilot_ctrl = Pilot_control()
