#!/usr/bin/env python
#----------------------------------------------------------------------
# A very simple wxPython example.  Just a wx.Frame, wx.Panel,
# wx.StaticText, wx.Button, and a wx.BoxSizer, but it shows the basic
# structure of any wxPython application.
#----------------------------------------------------------------------


import wx, datetime, time, sys, os
from string import *

def log(msgs):
    fd = open("wxlog2.txt", "a")
    fd.write(msgs)
    fd.write("\n")
    fd.close()

class MyFrame(wx.Frame):
    """
    This is MyFrame.  It just shows a few controls on a wxPanel,
    and has a simple menu.
    """
    def spacer(self, panel):
        self.sizer.Add(wx.StaticText(panel, -1, " "), 0, wx.ALL)
        
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, -1, title, pos=(100,100), size=(530, 480))
        # Create the menubar
        menuBar = wx.MenuBar()

        # and a menu 
        menu = wx.Menu()

        # add an item to the menu, using \tKeyName automatically
        # creates an accelerator, the third param is some help text
        # that will show up in the statusbar
        menu.Append(wx.ID_EXIT, "E&xit\tAlt-X", "Exit this simple sample")

        # bind the menu event to an event handler
        self.Bind(wx.EVT_MENU, self.OnTimeToClose, id=wx.ID_EXIT)

        # and put the menu on the menubar
        menuBar.Append(menu, "&File")
        self.SetMenuBar(menuBar)

        self.CreateStatusBar()
        # Now create the Panel to put the other controls on. 
        self.fsw_dictionary_directory = "/msop/mpcs/dict/"
        self.fsw_dictionary_version = "current"
        
        self.do_chill_monitor = False
        self.pers_directory = "/gds/msl/perspectives/Flight-Ground"
        self.pers_file = "PerspectiveFile.xml"
 
        panel = wx.Panel(self)
        
        user = os.environ['USER']
 
        self.jmsSubtopic = "PLAYBACK_%s" % upper(user)
        self.jmsSubtopic_widget = wx.TextCtrl(panel, -1, self.jmsSubtopic, size=(240, 20))
        panel.Bind(wx.EVT_TEXT, self.JmsSubtopic, self.jmsSubtopic_widget)
        
        self.databaseHost = ""
        self.databaseHost_widget = wx.TextCtrl(panel, -1, self.databaseHost, size=(240, 20))
        panel.Bind(wx.EVT_TEXT, self.DatabaseHost, self.databaseHost_widget)
        
        self.databasePort = ""
        self.databasePort_widget = wx.TextCtrl(panel, -1, self.databasePort, size=(240, 20))
        panel.Bind(wx.EVT_TEXT, self.DatabasePort, self.databasePort_widget)

        self.jmsHost = "mslbluejms1"
        self.jmsHost_widget = wx.TextCtrl(panel, -1, self.jmsHost, size=(240, 20))
        panel.Bind(wx.EVT_TEXT, self.JmsHost, self.jmsHost_widget)

        self.jmsPort = ""
        self.jmsPort_widget = wx.TextCtrl(panel, -1, self.jmsPort, size=(240, 20))
        panel.Bind(wx.EVT_TEXT, self.JmsPort, self.jmsPort_widget) 
               
        self.testUserPattern = ""
        self.testUserPattern_widget = wx.TextCtrl(panel, -1, self.testUserPattern, size=(240, 20))
        panel.Bind(wx.EVT_TEXT, self.TestUserPattern, self.testUserPattern_widget)

        self.testHostPattern = ""
        self.testHostPattern_widget = wx.TextCtrl(panel, -1, self.testHostPattern, size=(240, 20))
        panel.Bind(wx.EVT_TEXT, self.TestHostPattern, self.testHostPattern_widget)

        self.beginTime = ""
        self.beginTime_widget = wx.TextCtrl(panel, -1, self.beginTime, size=(240, 20))
        panel.Bind(wx.EVT_TEXT, self.BeginTime, self.beginTime_widget)
        
        self.endTime = ""
        self.endTime_widget = wx.TextCtrl(panel, -1, self.endTime, size=(240, 20))
        panel.Bind(wx.EVT_TEXT, self.EndTime, self.endTime_widget)

        self.testKey = ""
        self.testKey_widget = wx.TextCtrl(panel, -1, self.testKey, size=(240, 20))
        panel.Bind(wx.EVT_TEXT, self.TestKey, self.testKey_widget)
        
        self.meter = "5.0"
        self.meter_widget = wx.TextCtrl(panel, -1, self.meter, size=(240, 20))
        panel.Bind(wx.EVT_TEXT, self.Meter, self.meter_widget)
               
        # and a few controls
        self.dict_dir_label = wx.StaticText(panel, -1, " Dict Dir: ")
        self.dict_ver_label = wx.StaticText(panel, -1, " Dict Version: ")
        self.dict_dir = wx.TextCtrl(panel, -1, self.fsw_dictionary_directory, size=(240, 20))
        #dict_dir.setInsertionPoint(0)
        self.browse_button = wx.Button(panel, -1, " Browse ")
        self.dict_ver_choice_button = wx.Choice(panel, -1, (100, 50), choices=['current', 'sidebar'])
        pos = 0
        dirs = os.listdir(".")
        for direct in dirs:
           if direct.startswith('.'):
               continue
           if not os.path.isdir("%s/%s" % (self.fsw_dictionary_directory,direct)):
               log("is not a directory %s" % direct)
               continue
           self.dict_ver_choice_button.Insert(direct, pos)
           pos += 1
           log("do %s" % direct)
        self.dict_ver_choice_button.SetSelection(0)
        panel.Bind(wx.EVT_BUTTON, self.OnBrowseButton, self.browse_button)
        panel.Bind(wx.EVT_TEXT, self.DictDirText, self.dict_dir)
        panel.Bind(wx.EVT_TEXT_ENTER, self.DictDirTextEnter, self.dict_dir)
        panel.Bind(wx.EVT_CHOICE, self.DictVersionChoice, self.dict_ver_choice_button)
        
        self.start_chill_monitor_label = wx.StaticText(panel, -1, " Start Chill Monitor? ")       
        self.start_chill_monitor = wx.Choice(panel, -1, (100, 50), choices=['no', 'yes'])
        panel.Bind(wx.EVT_CHOICE, self.Start_Chill_Monitor, self.start_chill_monitor)
 
         # and a few controls
        self.pers_label = wx.StaticText(panel, -1, " Prespective: ")
        self.pers_item_value_widget = wx.TextCtrl(panel, -1, self.pers_directory + "/" + self.pers_file, size=(240, 20))
        panel.Bind(wx.EVT_TEXT, self.PersText, self.pers_item_value_widget)
        self.pers_button = wx.Button(panel, -1, "Open", size=(120, 20))
        panel.Bind(wx.EVT_BUTTON, self.PersBrowseButton, self.pers_button)
        #dict_dir.setInsertionPoint(0)

        self.submit_widget = wx.Button(panel, -1, "Make it so.")

        panel.Bind(wx.EVT_BUTTON, self.Submit, self.submit_widget)
 
        # Use a sizer to layout the controls, stacked vertically and with
        # a 10 pixel border around each
        self.sizer = wx.FlexGridSizer(rows=3,cols=3,hgap=4,vgap=4)
        self.spacer(panel)
        self.sizer.Add(wx.StaticText(panel, -1, "Playback Recorded Data"), 0, wx.ALL)
        self.spacer(panel)
       
        self.sizer.Add(wx.StaticText(panel, -1, " Parameters"))
        self.spacer(panel)
        self.spacer(panel)
 
        self.sizer.Add(wx.StaticText(panel, -1, "....JMS Sub-topic: "), 0, wx.ALL)
        self.sizer.Add(self.jmsSubtopic_widget, 0, wx.ALL)
        self.spacer(panel) 
              
        self.sizer.Add(wx.StaticText(panel, -1, "....Test Key: "), 0, wx.ALL)
        self.sizer.Add(self.testKey_widget, 0, wx.ALL)
        self.spacer(panel)
 
        self.sizer.Add(wx.StaticText(panel, -1, "....Meter: "), 0, wx.ALL)
        self.sizer.Add(self.meter_widget, 0, wx.ALL)
        self.sizer.Add(wx.StaticText(panel, -1, "in seconds per record"), 0, wx.ALL)
        
        self.sizer.Add(wx.StaticText(panel, -1, "....Test Host Pattern: "), 0, wx.ALL)
        self.sizer.Add(self.testHostPattern_widget, 0, wx.ALL)
        self.spacer(panel)
        
        self.sizer.Add(wx.StaticText(panel, -1, "....Test User Pattern: "), 0, wx.ALL)
        self.sizer.Add(self.testUserPattern_widget, 0, wx.ALL)
        self.spacer(panel)     
      
        self.sizer.Add(wx.StaticText(panel, -1, "....Database Host: "), 0, wx.ALL)
        self.sizer.Add(self.databaseHost_widget, 0, wx.ALL)
        self.spacer(panel)

        self.sizer.Add(wx.StaticText(panel, -1, "....Database Port: "), 0, wx.ALL)
        self.sizer.Add(self.databasePort_widget, 0, wx.ALL)
        self.spacer(panel)   
        
        self.sizer.Add(wx.StaticText(panel, -1, "....JMS Host: "), 0, wx.ALL)
        self.sizer.Add(self.jmsHost_widget, 0, wx.ALL)
        self.spacer(panel)

        self.sizer.Add(wx.StaticText(panel, -1, "....JMS Port: "), 0, wx.ALL)
        self.sizer.Add(self.jmsPort_widget, 0, wx.ALL)
        self.spacer(panel)   
        
        self.sizer.Add(wx.StaticText(panel, -1, "....Begin Time: "), 0, wx.ALL)
        self.sizer.Add(self.beginTime_widget, 0, wx.ALL)
        self.sizer.Add(wx.StaticText(panel, -1, "in ERT"), 0, wx.ALL)

        self.sizer.Add(wx.StaticText(panel, -1, "....End Time: "), 0, wx.ALL)
        self.sizer.Add(self.endTime_widget, 0, wx.ALL)
        self.sizer.Add(wx.StaticText(panel, -1, "in ERT"), 0, wx.ALL)


        #sizer.AddGrowableCol(1)
        #sizer.Add(btn, 0,  wx.EXPAND)
        #sizer.Add(funbtn, 0, wx.ALL, 103
        self.sizer.Add(self.dict_dir_label, 0, wx.ALL)
        self.sizer.Add(self.dict_dir, 0,  wx.ALL)
        self.sizer.Add(self.browse_button, 0, wx.ALL)
        self.sizer.Add(self.dict_ver_label, 0, wx.ALL)
        self.sizer.Add(self.dict_ver_choice_button, 0, wx.ALL)
        self.spacer(panel)
        
        self.sizer.Add(self.start_chill_monitor_label, 0, wx.ALL)
        self.sizer.Add(self.start_chill_monitor, 0, wx.ALL) 
        self.spacer(panel)       
        
        self.sizer.Add(self.pers_label, 0, wx.ALL)
        self.sizer.Add(self.pers_item_value_widget, 0,  wx.ALL)
        self.sizer.Add(self.pers_button, 0, wx.ALL)

        self.spacer(panel)
        self.sizer.Add(self.submit_widget, 0, wx.ALL)
        self.spacer(panel)
        
        panel.SetSizer(self.sizer)
        panel.Layout()
        self.main_panel = panel

        
    def OnTimeToClose(self, evt):
        """Event handler for the button click."""
        print "See ya later!"
        self.Close()
    def DictDirText(self, evt):
       log("DictDirText %s" % evt.GetString())
       self.fsw_dictionary_directory = evt.GetString()
       pass
    def PersText(self, evt):
       log("DictDirText %s" % evt.GetString())
       self.pers_file = evt.GetString()
       pass
       
    def DictDirTextEnter(self, evr):
       log("DictDirTextEnter")
       evr.skip()
       pass

    def TestHostPattern(self, evt):
        self.testHostPattern = evt.GetString()
    def TestUserPattern(self, evt):
        self.testUserPattern = evt.GetString() 
    def DatabaseHost(self, evt):
        self.databaseHost = evt.GetString()
    def DatabasePort(self, evt):
        self.databasePort = evt.GetString()
    def JmsHost(self, evt):
        self.jmsHost = evt.GetString()
    def JmsPort(self, evt):
        self.jmsPort = evt.GetString()
    def BeginTime(self, evt):
        self.beginTime = evt.GetString()
    def EndTime(self, evt):
        self.endTime = evt.GetString()
    def TestKey(self, evt):
        self.testKey = evt.GetString()
    def Meter(self, evt):
        self.meter = evt.GetString()
    def JmsSubtopic(self, evt):
        self.jmsSubtopic = evt.GetString()
    def DictVersionChoice(self, event):
       self.fsw_dictionary_version = event.GetString()
       log("DictVersionChoice, %s" % event.GetString())


    def OnBrowseButton(self, evt):
       dlg = wx.DirDialog(self, "Choose a FSW Dictionary Directory",defaultPath=self.fsw_dictionary_directory, style=wx.DD_DIR_MUST_EXIST)
       if dlg.ShowModal() == wx.ID_OK:
           self.fsw_dictionary_directory = dlg.GetPath()
           self.dict_dir.SetValue(dlg.GetPath())
           dirs = os.listdir(dlg.GetPath() + "/msl/")
           log("OnBrowseButton")
           log("dirs %s" % dirs)
           log("out of OnBrowseButton")
           self.dict_ver_choice_button.Clear()
           pos = 0
           for direct in dirs:
               if direct.startswith('.'):
                   continue
               if not os.path.isdir("%s/%s" % (self.fsw_dictionary_directory,direct)):
                   log("is not a directory %s" % direct)
                   continue
               self.dict_ver_choice_button.Insert(direct, pos)
               pos += 1
               log("do %s" % direct)
           self.dict_ver_choice_button.SetSelection(0)
       dlg.Destroy()
       self.Refresh()
    def Start_Chill_Monitor(self, evt):
       log("Start Chill Monitor %s" % evt.GetString())
       self.start_chill_monitor = evt.GetString() == "yes"
    def PersBrowseButton(self, evt):
       log("persbrowsebutton")
       dlg = wx.FileDialog(self, "Choose a Perspective: ",self.pers_directory,self.pers_file,"*.xml",wx.FD_OPEN)
       log("post file dialog")
       if dlg.ShowModal() == wx.ID_OK:
           self.pers_directory=dlg.GetDirectory()
           self.pers_file=dlg.GetFilename()
       dlg.Destroy()
       self.Refresh()
 
    def Submit(self, evr):
       cmdln = []
       cmdln.append("/home/jwright/rt_rec_playback.rb")
       if self.fsw_dictionary_directory != "":
           cmdln.append("--fswDictionaryDir %s" % self.fsw_dictionary_directory)
       if self.fsw_dictionary_version != "":
           cmdln.append("--fswVersion %s" % self.fsw_dictionary_version)
       if self.testHostPattern != "":
           cmdln.append("--testHostPattern %s" % self.testHostPattern)
       if self.testUserPattern != "":
           cmdln.append("--testUserPattern %s" % self.testUserPattern)
       if self.databaseHost != "":
           cmdln.append("--databaseHost %s" % self.databaseHost)
       if self.databasePort != "":
           cmdln.append("--databasePort %s" % self.databasePort)
       if self.jmsHost != "":
           cmdln.append("--jmsHost %s" % self.jmsHost)
       if self.jmsPort != "":
           cmdln.append("--jmsPort %s" % self.jmsPort)
       if self.beginTime != "":
           cmdln.append("--beginTime %s" % self.beginTime)
       if self.endTime != "":
           cmdln.append("--endTime %s" % self.endTime)
       if self.testKey != "":
           cmdln.append("--testKey %s" % self.testKey)
       cmdln.append("--jmsSubTopic %s" % self.jmsSubtopic)
       cmd = " ".join(cmdln)
       self.main_panel.Destroy()
       print "cmd %s" % cmd
       os.system(cmd)
       exit(1)

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, "Playback Engineering Data")
        self.SetTopWindow(frame)
        frame.Show(True)
        return True
        
app = MyApp(redirect=False)
app.MainLoop()

