def Setup(self, collection_type):
     self.collection_type = collection_type
     try:
         # get output directory
         print "here 0"
         chem_dir = self.director.GetBiochemicalFileDirectory()
         # print "chem_dir: "+chem_dir
         try:
             os.makedirs(chem_dir)
         except OSError as exc: # Python >2.5
             if exc.errno == errno.EEXIST and os.path.isdir(chem_dir):
                 pass
             else: raise
         # open output files
         if self.collection_type == "baseline":
             chem_file_1_path = os.path.join(chem_dir,"baseline_chem_file_1")
         else:
             chem_file_1_path = os.path.join(chem_dir,"chem_file_1")
         self.chem_file_1 = open(chem_file_1_path,"w")
         # load configuration parameters into sensor
         aController = AlgorithmController(self.db, Algorithm, None, None)
         adController = AlgorithmDefaultsController(self.db, AlgorithmDefaults, None, None)
         algorithm = aController.getByName("biochemical sensor")
         # (names,values) = adController.getAllAsLists(algorithm.id)
         # self.sensor.createConfiguration(names, values)
         # self.sensor.configure()
         nReps = int(adController.getDefaultByName("numberReps", algorithm.id))
         print "Configuring biochemical sensor for %d repetitions" % (nReps)
         self.sensor.configure(nReps)
     except PUFileDirectorException as e:
         self.message = e.to_string()
     except pu.BiochemicalSensorException as e:
         self.message = e.what()
     except Exception as e:
         print "Exception - ",e
         self.message = e
    def __init__(self, parent, db, mode="Add-Update-Delete"):
        """
        Constructor which creates the modal dialog and its widgets, instantiates an
        ObjectlistView and populates it with the results from a query containing all
        database objects in a class.
        Arguments:
            parent - Parent window
            db - Database connection object
            mode - Dialog mode which can be either "Add-Update-Delete" or "Select"
        """
        self.db = db
        self.obj = Algorithm
        self.objOlv = OlvAlgorithm
        self.objOlvCols = OlvAlgorithmCols()
        width = self.objOlvCols.getTotalColumnWidth()
        wx.Dialog.__init__(self, parent, size=wx.Size(width,500))
        self.controller = AlgorithmController(db, self.obj, self.objOlv, self.objOlvCols)
        try:
            self.results = self.controller.getAllRecords()
        except:
            self.results = []
        
        font = wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.BOLD) 
        lbl = wx.StaticText(self, label=self.obj.displayTableName)
        lbl.SetFont(font)

        mainSizer = wx.BoxSizer(wx.VERTICAL)
        searchSizer = wx.BoxSizer(wx.HORIZONTAL)
        btnSizer = wx.BoxSizer(wx.HORIZONTAL)
        font = wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD) 
        
        # create the search related widgets
        searchByLbl = wx.StaticText(self, label="Search By:")
        searchByLbl.SetFont(font)
        searchSizer.Add(searchByLbl, 0, wx.ALL, 5)
        
        self.search = wx.SearchCtrl(self, style=wx.TE_PROCESS_ENTER)
        self.search.Bind(wx.EVT_TEXT_ENTER, self.onSearch)
        searchSizer.Add(self.search, 0, wx.ALL, 5)
        
        self.resultsOlv = ObjectListView(self, style=wx.LC_REPORT
                                                        |wx.SUNKEN_BORDER)
        self.resultsOlv.SetEmptyListMsg("No Records Found")
        self.setResultsOlv()
        
        # create the button row
        if mode == "Select-Only":
            selectRecordBtn = wx.Button(self, label="Select")
            selectRecordBtn.Bind(wx.EVT_BUTTON, self.onSelectRecord)
            btnSizer.Add(selectRecordBtn, 0, wx.ALL, 5)
        
        if mode == "Add-Update-Delete":
            addRecordBtn = wx.Button(self, label="Add")
            addRecordBtn.Bind(wx.EVT_BUTTON, self.onAddRecord)
            btnSizer.Add(addRecordBtn, 0, wx.ALL, 5)
        
            editRecordBtn = wx.Button(self, label="Edit")
            editRecordBtn.Bind(wx.EVT_BUTTON, self.onEditRecord)
            btnSizer.Add(editRecordBtn, 0, wx.ALL, 5)
        
            deleteRecordBtn = wx.Button(self, label="Delete")
            deleteRecordBtn.Bind(wx.EVT_BUTTON, self.onDelete)
            btnSizer.Add(deleteRecordBtn, 0, wx.ALL, 5)
        
        showAllBtn = wx.Button(self, label="Show All")
        showAllBtn.Bind(wx.EVT_BUTTON, self.onShowAllRecord)
        btnSizer.Add(showAllBtn, 0, wx.ALL, 5)
        
        configBtn = wx.Button(self, label="Configuration")
        configBtn.Bind(wx.EVT_BUTTON, self.onConfiguration)
        btnSizer.Add(configBtn, 0, wx.ALL, 5)
        
        experimentsBtn = wx.Button(self, label="Experiments")
        experimentsBtn.Bind(wx.EVT_BUTTON, self.onExperiments)
        btnSizer.Add(experimentsBtn, 0, wx.ALL, 5)
        
        mainSizer.Add(lbl, 0, wx.CENTER)
        mainSizer.Add(searchSizer)
        mainSizer.Add(self.resultsOlv, 1, wx.ALL|wx.EXPAND, 5)
        mainSizer.Add(btnSizer, 0, wx.CENTER)
        self.SetSizer(mainSizer)
class AlgorithmDialog(wx.Dialog):
    """
    This class implements the generic select/add/update/delete dialog for a database object.
    It constructs the list of objects and places them in an ObjectListView widget.
    It then implements the button handlers for calling the add_modify_dialog to add or modify
    the object. Selection and deletion are handled in this dialog by calling the
    olv_dialog_controller controller.
    Methods:
        __init__(parent, db, obj, objOlv, objOlvCols, mode) - creates the widgets in the panel and performs initialization
        getSelectedObject() - Gets the selected object in the ObjectListView
        onAddRecord(event) - Button handler to add a record to the database
        onEditRecord(event) - Button handler to edit a record
        onDeleteRecord(event) - Button handler to delete a record
        onSearch(event) - Search field handler to search database based on the user's filter choice and keyword
        onSelectRecord(event) - Button handler to select a record
        onShowAllRecord(event) - Button handler to update the record list to show all of them
        setResultsOlv() - Sets the columns and objects in the ObjectListView
        showAllRecords() - Shows all records in the object list view control
    """

    #----------------------------------------------------------------------
    def __init__(self, parent, db, mode="Add-Update-Delete"):
        """
        Constructor which creates the modal dialog and its widgets, instantiates an
        ObjectlistView and populates it with the results from a query containing all
        database objects in a class.
        Arguments:
            parent - Parent window
            db - Database connection object
            mode - Dialog mode which can be either "Add-Update-Delete" or "Select"
        """
        self.db = db
        self.obj = Algorithm
        self.objOlv = OlvAlgorithm
        self.objOlvCols = OlvAlgorithmCols()
        width = self.objOlvCols.getTotalColumnWidth()
        wx.Dialog.__init__(self, parent, size=wx.Size(width,500))
        self.controller = AlgorithmController(db, self.obj, self.objOlv, self.objOlvCols)
        try:
            self.results = self.controller.getAllRecords()
        except:
            self.results = []
        
        font = wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.BOLD) 
        lbl = wx.StaticText(self, label=self.obj.displayTableName)
        lbl.SetFont(font)

        mainSizer = wx.BoxSizer(wx.VERTICAL)
        searchSizer = wx.BoxSizer(wx.HORIZONTAL)
        btnSizer = wx.BoxSizer(wx.HORIZONTAL)
        font = wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD) 
        
        # create the search related widgets
        searchByLbl = wx.StaticText(self, label="Search By:")
        searchByLbl.SetFont(font)
        searchSizer.Add(searchByLbl, 0, wx.ALL, 5)
        
        self.search = wx.SearchCtrl(self, style=wx.TE_PROCESS_ENTER)
        self.search.Bind(wx.EVT_TEXT_ENTER, self.onSearch)
        searchSizer.Add(self.search, 0, wx.ALL, 5)
        
        self.resultsOlv = ObjectListView(self, style=wx.LC_REPORT
                                                        |wx.SUNKEN_BORDER)
        self.resultsOlv.SetEmptyListMsg("No Records Found")
        self.setResultsOlv()
        
        # create the button row
        if mode == "Select-Only":
            selectRecordBtn = wx.Button(self, label="Select")
            selectRecordBtn.Bind(wx.EVT_BUTTON, self.onSelectRecord)
            btnSizer.Add(selectRecordBtn, 0, wx.ALL, 5)
        
        if mode == "Add-Update-Delete":
            addRecordBtn = wx.Button(self, label="Add")
            addRecordBtn.Bind(wx.EVT_BUTTON, self.onAddRecord)
            btnSizer.Add(addRecordBtn, 0, wx.ALL, 5)
        
            editRecordBtn = wx.Button(self, label="Edit")
            editRecordBtn.Bind(wx.EVT_BUTTON, self.onEditRecord)
            btnSizer.Add(editRecordBtn, 0, wx.ALL, 5)
        
            deleteRecordBtn = wx.Button(self, label="Delete")
            deleteRecordBtn.Bind(wx.EVT_BUTTON, self.onDelete)
            btnSizer.Add(deleteRecordBtn, 0, wx.ALL, 5)
        
        showAllBtn = wx.Button(self, label="Show All")
        showAllBtn.Bind(wx.EVT_BUTTON, self.onShowAllRecord)
        btnSizer.Add(showAllBtn, 0, wx.ALL, 5)
        
        configBtn = wx.Button(self, label="Configuration")
        configBtn.Bind(wx.EVT_BUTTON, self.onConfiguration)
        btnSizer.Add(configBtn, 0, wx.ALL, 5)
        
        experimentsBtn = wx.Button(self, label="Experiments")
        experimentsBtn.Bind(wx.EVT_BUTTON, self.onExperiments)
        btnSizer.Add(experimentsBtn, 0, wx.ALL, 5)
        
        mainSizer.Add(lbl, 0, wx.CENTER)
        mainSizer.Add(searchSizer)
        mainSizer.Add(self.resultsOlv, 1, wx.ALL|wx.EXPAND, 5)
        mainSizer.Add(btnSizer, 0, wx.CENTER)
        self.SetSizer(mainSizer)
        # mainSizer.Fit(self)
        
    #----------------------------------------------------------------------
    def getSelectedObject(self):
        """
        Gets the selected object in the ObjectListView
        """
        return self.selectedObject
    
    #----------------------------------------------------------------------
    def onAddRecord(self, event):
        """
        Button handler to add a record to the database
        """
        dlg = add_modify_dialog.AddModifyDialog(self.controller, self.obj, title="Add", addRecord=True)
        rc = dlg.ShowModal()
        if rc == 0:
            self.showAllRecords()
        
    #----------------------------------------------------------------------
    def onEditRecord(self, event):
        """
        Button handler to edit a record
        """
        selectedRow = self.resultsOlv.GetSelectedObject()
        if selectedRow == None:
            util.showMessageDialog("No row selected!", "Error")
            return
        dlg = add_modify_dialog.AddModifyDialog(self.controller, self.obj, row=selectedRow, title="Modify",
                                           addRecord=False)
        rc = dlg.ShowModal()
        if rc == 0:
            self.showAllRecords()
        
    #----------------------------------------------------------------------
    def onDelete(self, event):
        """
        Button handler to delete a record
        """
        selectedRow = self.resultsOlv.GetSelectedObject()
        if selectedRow == None:
            util.showMessageDialog("No row selected!", "Error")
            return
        (rc, msg) = self.controller.deleteRecord(selectedRow.getKey())
        # Check return code from above and put up appropriate message dialog
        if rc == 0:
            util.showMessageDialog("Record Deleted Successfully!", "Success!", wx.ICON_INFORMATION)
        else:
            util.showMessageDialog(msg, "Failure!", wx.ICON_INFORMATION)
        self.showAllRecords()
        
    #----------------------------------------------------------------------
    def onConfiguration(self, event):
        """
        Button handler to show configuration parameters
        """
        selectedRow = self.resultsOlv.GetSelectedObject()
        if selectedRow == None:
            util.showMessageDialog("No row selected!", "Error")
            return
        algorithmId = selectedRow.getKey()
        olvDialog = AlgorithmDefaultsDialog(None, self.db, algorithmId)
        rc = olvDialog.ShowModal()
        olvDialog.Destroy()
        self.Enable()
        self.showAllRecords()

    #----------------------------------------------------------------------
    def onExperiments(self, event):
        """
        Button handler to show experiments for an algorithm
        """
        selectedRow = self.resultsOlv.GetSelectedObject()
        if selectedRow == None:
            util.showMessageDialog("No row selected!", "Error")
            return
        algorithmId = selectedRow.getKey()
        olvDialog = ExperimentDialog(None, self.db, algorithmId=algorithmId)
        rc = olvDialog.ShowModal()
        olvDialog.Destroy()
        self.Enable()
        self.showAllRecords()
        
    #----------------------------------------------------------------------
    def onSearch(self, event):
        """
        Search field handler to search database based on the user's filter choice and keyword
        """
        keyword = self.search.GetValue()
        Filter.TextSearch(self.resultsOlv,columns=(), text=keyword)
        
    #----------------------------------------------------------------------
    def onSelectRecord(self, event):
        """
        Button handler to select a record
        """
        selectedRow = self.resultsOlv.GetSelectedObject()
        if selectedRow == None:
            util.showMessageDialog("No row selected!", "Error")
            return
        key = selectedRow.getKey()
        self.selectedObject = self.controller.getRecordByKey(key)
        self.EndModal(0)
        
    #----------------------------------------------------------------------
    def onShowAllRecord(self, event):
        """
        Button handler to update the record list to show all of them
        """
        self.showAllRecords()
        
    #----------------------------------------------------------------------
    def setResultsOlv(self):
        """
        Sets the columns and objects in the ObjectListView
        """
        cd = self.objOlvCols.getColumnDefinitions()
        # print len(cd)
        self.resultsOlv.SetColumns(self.objOlvCols.getColumnDefinitions())
        self.resultsOlv.SetObjects(self.results)
        
    #----------------------------------------------------------------------
    def showAllRecords(self):
        """
        Shows all records in the object list view control
        """
        self.results = self.controller.getAllRecords()
        self.setResultsOlv()
 def __init__(self, controller, obj, db, row=None, title="Add", addRecord=True, algorithmId=None):
     """
     Initializes the add/modify dialog. This consists of constructing an input form
     which has field names and a text field for entering field values.
     Arguments:
         controller - class performing the object creation, update, or deletion
         obj - object class to be processed
         row - row selected containing the object
         title - title to be displayed on form
         addRecord - flag indicating that a new record is to be created
     """
     # set up controllers
     algorithmController = AlgorithmController(db, Algorithm, None, None)
     
     wx.Dialog.__init__(self, None, title="%s Experiment Record" % title)
     self.controller = controller
     if row:
         key = row.getKey()
         self.objInstance = controller.getRecordByKey(key)
         if addRecord:
             curAlgorithmtId = self.objInstance.algorithm_id
             self.objInstance = obj()
             self.objInstance.patient_id = curAlgorithmtId
     else:
         self.objInstance = obj()
         self.objInstance.algorithm_id = algorithmId
     self.addRecord = addRecord
     self.selectedRow = row
     size = (80, -1)
     font = wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.BOLD) 
     
     # create the sizers
     mainSizer = wx.BoxSizer(wx.VERTICAL)
     btnSizer = wx.BoxSizer(wx.HORIZONTAL)
             
     # create some widgets
     lbl = wx.StaticText(self, label=self.objInstance.displayTableName)
     lbl.SetFont(font)
     mainSizer.Add(lbl, 0, wx.CENTER)
     font = wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD)
     
     self.ctls = []
     lbl = wx.StaticText(self, size=size)
     lbl.SetLabel("Experiment Name:")
     lbl.SetFont(font)
     if row:
         self.experimentTextCtrl = wx.TextCtrl(self, value=row.experiment_name)
     else:
         self.experimentTextCtrl = wx.TextCtrl(self, value="")
     mainSizer.Add(self.rowBuilder([lbl, self.experimentTextCtrl]), 0, wx.EXPAND)
     
     lbl = wx.StaticText(self, size=size)
     lbl.SetLabel("Algorithm:")
     lbl.SetFont(font)
     self.algorithm_name = wx.ComboBox(self, wx.ID_ANY, choices=[], style=wx.CB_DROPDOWN | wx.CB_DROPDOWN)
     self.algorithm_name.SetFont(font)
     algorithms = algorithmController.getAll()
     for s in algorithms:
         self.algorithm_name.Append(s.algorithm_name, str(s.id))
     if row:
         n = 0
         for s in algorithms:
             if self.objInstance.algorithm_id == s.id:
                 self.algorithm_name.Select(n)
                 break
             n = n + 1
     else:
         self.algorithm_name.Select(0)
     mainSizer.Add(self.rowBuilder([lbl, self.algorithm_name]), 0, wx.EXPAND)
     
     lbl = wx.StaticText(self, size=size)
     lbl.SetLabel("Default?:")
     lbl.SetFont(font)
     self.defCheckbox = wx.CheckBox(self)
     if row and not(self.addRecord) and self.objInstance.default_flag == 1:
         self.defCheckbox.SetValue(True)
     mainSizer.Add(self.rowBuilder([lbl, self.defCheckbox]), 0, wx.EXPAND)
     
     lbl = wx.StaticText(self, size=size)
     lbl.SetLabel("Description:")
     lbl.SetFont(font)
     if row and not(self.addRecord) and not(self.objInstance.experiment_description is None):
         self.descTextCtrl = wx.TextCtrl(self, value=self.objInstance.experiment_description)
     else:
         self.descTextCtrl = wx.TextCtrl(self, value="")
     mainSizer.Add(self.rowBuilder([lbl, self.descTextCtrl]), 0, wx.EXPAND)
     
     okBtn = wx.Button(self, label="%s" % title)
     okBtn.Bind(wx.EVT_BUTTON, self.onRecord)
     btnSizer.Add(okBtn, 0, wx.ALL, 5)
     cancelBtn = wx.Button(self, label="Close")
     cancelBtn.Bind(wx.EVT_BUTTON, self.onClose)
     btnSizer.Add(cancelBtn, 0, wx.ALL, 5)
     
     mainSizer.Add(btnSizer, 0, wx.CENTER)
     self.SetSizer(mainSizer)
     self.Refresh()