import sys
import time
import threading
import wx

from dlg import G2MultiChoiceDialog
import wxsim

dlgResults = {}
def ShowAsNonModal(dlg,callback):
    def handle_dialog_end_ok():
        dlgResults['selected'] = dlg.GetSelections()
        print('Selected:', dlgResults['selected'])
        dlg.Destroy()
        parent.Enable()
        if callback:
            wx.CallLater(500, callback)
    def handle_dialog_end_cancel():
        dlgResults['selected'] = None
        dlg.Destroy()
        parent.Enable()
        raise Exception("Cancel button pressed")

    def on_ok(event):
        event.Skip()
        handle_dialog_end_ok()
    
    def on_cancel(event):
        event.Skip()
        handle_dialog_end_cancel()
    
    def on_close(event):
        event.Skip()
        handle_dialog_end_cancel()
        
    # Bind to both button events and window close
    dlg.Bind(wx.EVT_BUTTON, on_ok, id=wx.ID_OK)
    dlg.Bind(wx.EVT_BUTTON, on_cancel, id=wx.ID_CANCEL)
    dlg.Bind(wx.EVT_CLOSE, on_close)

    parent = dlg.GetParent()
    parent.Disable()  # Disable main window while dialog is open
    dlg.Show()
            
def openSelect(event):
    '''launches `wxsim.pressButtonsInWindow` in a thread then opens a modal window
    with `OpenDialog`. `wxsim.pressButtonsInWindow` simulates pressing two buttons
    in the dialog, where the second closes the dialog.

    Does this twice, just to prove I can.
    '''
    choices = ['Bi1', 'O1', 'Cl1']
    
    def on_dialog_shown(dlg):
        # Start automation after dialog is shown and had time to render
        wx.CallLater(200, lambda: threading.Thread(target=wxsim.pressButtonsInWindow,
            args=('Select atoms for action',['Set All','OK'])).start())
    
    def start_second_dialog():
        # Show second dialog and set up its automation
        dlgResults.clear()
        dlg = G2MultiChoiceDialog(None,'Select atoms',
                'Select atoms for action',choices)
        on_dialog_shown(dlg)
        ShowAsNonModal(dlg,None)

    # Show first dialog and set up its automation
    dlgResults.clear()
    dlg = G2MultiChoiceDialog(None,'Select atoms',
            'Select atoms for action',choices)
    on_dialog_shown(dlg)
    ShowAsNonModal(dlg,start_second_dialog)

app = wx.App()
frm = wx.Frame(None)
ms = wx.BoxSizer(wx.VERTICAL)
btn = wx.Button(frm,wx.ID_ANY,'Open modal window')
btn.Bind(wx.EVT_BUTTON,openSelect)
ms.Add(btn)
frm.SetSizer(ms)
frm.Show(True)
app.MainLoop()
