import wx
import os,sys
import thread
global pygame # when we import it, let's keep its proper name!

class SDLThread:
    def __init__(self,screen):
        self.m_bKeepGoing = self.m_bRunning = False
        self.screen = screen
        self.color = (255,0,0)
        self.rect = (10,10,100,100)

    def Start(self):
        self.m_bKeepGoing = self.m_bRunning = True
        thread.start_new_thread(self.Run, ())

    def Stop(self):
        self.m_bKeepGoing = False

    def IsRunning(self):
        return self.m_bRunning

    def Run(self):
        while self.m_bKeepGoing:
            e = pygame.event.poll()
            if e.type == pygame.MOUSEBUTTONDOWN:
                self.color = (255,0,128)
                self.rect = (e.pos[0], e.pos[1], 100, 100)
                print e.pos
            self.screen.fill((0,0,0))
            self.screen.fill(self.color,self.rect)
            pygame.display.flip()
        self.m_bRunning = False;

class SDLPanel(wx.Panel):
    def __init__(self,parent,ID,tplSize):
        global pygame
        wx.Panel.__init__(self, parent, ID, size=tplSize)
        self.Fit()
        os.environ['SDL_WINDOWID'] = str(self.GetHandle())
        os.environ['SDL_VIDEODRIVER'] = 'windib'
        import pygame # this has to happen after setting the environment variables.
        pygame.display.init()
        window = pygame.display.set_mode(tplSize)
        self.thread = SDLThread(window)
        self.thread.Start()

    def __del__(self):
        self.thread.Stop()

class mainWindow(wx.Frame):
    def __init__(self, parent, ID, strTitle, tplSize):
        wx.Frame.__init__(self, parent, ID, strTitle, size=tplSize)
        self.mainmenu = wx.MenuBar()   # Create menu bar.
        self.menu=wx.Menu()      
        
        self.exitID=wx.NewId()        
        self.menu.Append(self.exitID, 'E&xit', 'Exit program')        
        wx.EVT_MENU(self, self.exitID, self.OnExit)
        self.mainmenu.Append (self.menu, '&File')
        self.SetMenuBar (self.mainmenu)
        
        self.notebook = wx.Notebook(self,-1)

        self.tab1 = wx.Panel(self.notebook,-1)
        self.notebook.AddPage(self.tab1,"Add Notes1")
        
        self.tab2 = SDLPanel(self.notebook, -1, tplSize)
        self.notebook.AddPage(self.tab2,"Add Notes4")
        
        self.tab3 = wx.Panel(self.notebook,-1)
        self.notebook.AddPage(self.tab3,"Add Notes3")
        
        #self.Fit()

    def OnExit(self,event):
        self.Close()
        self.Destroy()
        sys.exit(0)

#######MAIN APP#######      
   
class App(wx.App):
    def OnInit(self):
        nextFrame = mainWindow(None,-1,"WX in pygame",(800,600))
        nextFrame.Show()
        self.SetTopWindow(nextFrame)
        return True

if __name__=="__main__":
    app=App(0)
    app.MainLoop()
