import wx
import sys
import time
import threading
import os


class TestDialog(wx.Dialog):
    def __init__(self, parent, ID, title):
        wx.Dialog.__init__(self, parent, ID, title)

        boxSizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(boxSizer)

        okButton = wx.Button(self, wx.ID_OK)

        boxSizer.Add(okButton)
        boxSizer.Fit(self)


class TestApp(wx.App):
    def __init__(self):
        wx.App.__init__(self, redirect=False)

    def OnInit(self):

        def testWorker1():
            print "testWorker1: Writing stdout from " + \
                threading.current_thread().name
            wx.CallAfter(sys.stdout.write,
                         "testWorker1: Writing stdout from MainThread.\n")
            time.sleep(5)
        testWorker1Thread = threading.Thread(target=testWorker1,
                                             name="TestWorker1Thread")
        testWorker1Thread.start()

        testDialog = TestDialog(None, wx.ID_ANY, "Test Dialog")
        if testDialog.ShowModal() == wx.ID_OK:
            print "TestDialog returned wx.ID_OK. Thread is " + \
                threading.current_thread().name

        def testWorker2():
            print "testWorker2: Writing stdout from " + \
                threading.current_thread().name
            wx.CallAfter(sys.stdout.write,
                         "testWorker2: Writing stdout from MainThread.\n")
            time.sleep(5)
            os._exit(0)

        testWorker2Thread = threading.Thread(target=testWorker2,
                                             name="TestWorker2Thread")
        testWorker2Thread.start()

        return True


def main(argv):
    app = TestApp()
    app.MainLoop()

if __name__ == "__main__":
    main(sys.argv)
