#pragma warning(disable: 4819)
#pragma warning(disable: 4100)

#include <monitor.h>


inline void SDLPanel::OnEraseBackground(wxEraseEvent &) {}

IMPLEMENT_CLASS(SDLPanel, wxPanel)

BEGIN_EVENT_TABLE(SDLPanel, wxPanel)
    EVT_PAINT(SDLPanel::OnPaint)
    EVT_ERASE_BACKGROUND(SDLPanel::OnEraseBackground)
    EVT_IDLE(SDLPanel::OnIdle)
	EVT_SIZE(SDLPanel::OnSize)
END_EVENT_TABLE()

SDLPanel::SDLPanel(wxWindow *parent) : wxPanel(parent, -1), surface(NULL) {
    // ensure the size of the wxPanel
    wxSize size(WIDTH, HEIGHT);
    
    SetMinSize(size);
    SetMaxSize(size);
	
    wxIdleEvent event;  
    event.SetEventObject(this);  
    this->AddPendingEvent(event);  
	
	//seed = 0x12345;
}

SDLPanel::~SDLPanel() {
    if (surface != NULL) {
        SDL_FreeSurface(surface);
    }
}

void SDLPanel::OnPaint(wxPaintEvent &) {
    // can't draw if the surface doesn't exist yet
    if (surface == NULL) {
        return;
    }
    
	Lock();
    
    // create a bitmap from our pixel data
    wxBitmap bmp(wxImage(surface->w, surface->h, 
                    static_cast<unsigned char *>(surface->pixels), true));
    
	Unlock();
    
    // paint the surface
    wxBufferedPaintDC dc(this, bmp);
}

void SDLPanel::Update()
{
	wxBitmap bmp(wxImage(surface->w, surface->h, 
		static_cast<unsigned char *>(surface->pixels), true));
    wxBufferedPaintDC dc(this, bmp);
}

void SDLPanel::Lock()
{
    // Lock surface if needed
    if (SDL_MUSTLOCK(surface)) {
        if (SDL_LockSurface(surface) < 0) {
            return;
        }
    }
}

void SDLPanel::Unlock()
{
    // Unlock if needed
    if (SDL_MUSTLOCK(surface)) {
        SDL_UnlockSurface(surface);
    }
}

SDL_Surface *SDLPanel::GetSurface()
{
    return surface;
}

void SDLPanel::OnIdle(wxIdleEvent &) {
    // create the SDL_Surface
    CreateSurface();
	
	//Lock();
	//Unlock();
}

void SDLPanel::CreateSurface() {
	GetClientSize(&_width, &_height); 

	if (surface == NULL) 
	{ 
		surface = SDL_CreateRGBSurface(SDL_HWSURFACE | SDL_DOUBLEBUF, 
				_width, _height, 32, 0, 0, 0, 0);      
	} 
	// Size has changed - nuke and redo. 
	else if( surface->w != _width || surface->h != _height ) 
	{ 
		SDL_FreeSurface( surface ); 
		surface = SDL_CreateRGBSurface(SDL_HWSURFACE | SDL_DOUBLEBUF, 
				_width, _height, 32, 0, 0, 0, 0);      
	} 
}

void SDLPanel::OnSize( wxSizeEvent& event ) 
{ 
	wxPanel::OnSize(event); 
	GetClientSize(&_width, &_height); 
	// Call createScreen to delete and recreate the surface. 
	CreateSurface(); 
	Refresh(); 
}
