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

#include <monitor.h>

BEGIN_EVENT_TABLE(SDLFrame, wxMDIChildFrame)
	EVT_IDLE(SDLFrame::OnIdle)
	EVT_CLOSE(SDLFrame::OnClose)
    EVT_SIZE(SDLFrame::OnSize)
END_EVENT_TABLE()
	
	
SDLFrame::SDLFrame(wxMDIParentFrame* parent,
	MonitorFrame *myFrame,
	wxWindowID id,
	const wxString& title,
	const wxPoint& pos,
	const wxSize& size,
	long style)
	: wxMDIChildFrame(parent, id, title, pos, size, style)
{
	this->myFrame = myFrame;

    m_panel = new SDLPanel(this);  
	
	wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL);
	sizer->Add(m_panel, 1, wxEXPAND|wxALL);
	SetSizer(sizer);
	
	//m_surface = m_panel->GetSurface();

    SetIcon(GET_ICON("monitor"));

	Layout();
    
	/*
	wxSize size(WIDTH, HEIGHT);
    
    SetMinSize(size);
    SetMaxSize(size);
	*/

    Show(true);
}

SDLFrame::~SDLFrame()
{
}

void SDLFrame::Init(int width, int height)
{
	m_width = width;
	m_height = height;

	m_buffer = (unsigned int *)calloc(m_width * m_height, sizeof(unsigned int));
	if (m_buffer == NULL) {
		// error
	}
	
	m_bufferSurface = SDL_CreateRGBSurfaceFrom(m_buffer, 
			m_width, m_height, 32, m_width*sizeof(unsigned int), 
			0, 0, 0, 0);
	m_blitSurface = m_bufferSurface;
}

void SDLFrame::Update(void *buffer)
{
	memcpy(m_bufferSurface->pixels, buffer, 
			m_width * m_height * sizeof(unsigned int));
	m_blitSurface = m_bufferSurface;

	int ret = SDL_BlitSurface(m_blitSurface, NULL, m_panel->GetSurface(), NULL);
	if (ret != 0) {
		// error
	}
	ret = SDL_Flip(m_panel->GetSurface());
	if (ret != 0) {
		// error
	}
}

void SDLFrame::Free()
{
	SDL_FreeSurface(m_bufferSurface);
	SDL_FreeSurface(m_panel->GetSurface());
	free(m_buffer);
}

int SDLFrame::GetWidth()
{
	return m_width;
}

int SDLFrame::GetHeight()
{
	return m_height;
}

SDL_Surface* SDLFrame::GetSurface()
{
	return m_panel->GetSurface();
}

void SDLFrame::Lock()
{
	m_panel->Lock();
}

void SDLFrame::Unlock()
{
	m_panel->Unlock();
}

void SDLFrame::OnSize(wxSizeEvent& event)
{
	//CONSOLE->Puts("aaaaa\n", ECSIM_STDOUT);
	wxSize size = GetClientSize();
	//m_vtkWin->UpdateSize(size.x, size.y);
}

void SDLFrame::OnIdle(wxIdleEvent& event)
{
    Refresh(false);
	Layout();
}

void SDLFrame::OnClose(wxCloseEvent& event)
{
	event.Veto();
	return;
}
