#include "scripteditor.h"


using namespace VRUT;

ScriptEditorDialog::ScriptEditorDialog( wxWindow* parent, wxWindowID id, const wxString& scriptCode, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style )
{
	this->SetSizeHints( wxDefaultSize, wxDefaultSize );
	wxBoxSizer* mainSizer = new wxBoxSizer( wxVERTICAL );

	scriptLabel = new wxStaticText( this, wxID_ANY, wxT("script source code"), wxDefaultPosition, wxDefaultSize, 0 );
	scriptLabel->Wrap( -1 );
	mainSizer->Add( scriptLabel, 0, wxALL|wxALIGN_CENTER_HORIZONTAL, 5 );

	scriptText = new wxTextCtrl( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(320,200), wxTE_PROCESS_ENTER | wxTE_MULTILINE );
	mainSizer->Add( scriptText, wxSizerFlags(1).Expand());

	wxBoxSizer* buttonSizer = new wxBoxSizer( wxHORIZONTAL );

	okButton = new wxButton( this, wxID_OK, wxT("Ok"), wxDefaultPosition, wxDefaultSize, 0 );
	buttonSizer->Add( okButton, 0, wxALL, 5 );

	cancelButton = new wxButton( this, wxID_CANCEL, wxT("Cancel"), wxDefaultPosition, wxDefaultSize, 0 );
	buttonSizer->Add( cancelButton, 0, wxALL, 5 );

	mainSizer->Add( buttonSizer, 0, wxALL| wxALIGN_BOTTOM, 5 );

	this->SetSizerAndFit( mainSizer );
	this->Layout();

	this->Centre( wxBOTH );

	okButton->Connect(wxID_ANY, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(ScriptEditorDialog::OnClick), NULL, this);
	cancelButton->Connect(wxID_ANY, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(ScriptEditorDialog::OnClick), NULL, this);

	scriptSourceCode = scriptCode;
	scriptText->SetValue(scriptSourceCode);

	KERNEL->WinPosSizeFromVRUTConfig(this, wxT("/ScriptEditorDialog/"), wxPoint(100, 100), wxSize(252, 130), true);
}

ScriptEditorDialog::~ScriptEditorDialog()
{
	KERNEL->WinPosSizeToVRUTConfig(this, wxT("/ScriptEditorDialog/"), true);
}

void ScriptEditorDialog::OnClick(wxCommandEvent &evt)
{
	if (evt.GetEventObject() == okButton)
	{
		scriptSourceCode = scriptText->GetValue();
		this->EndModal(wxID_OK);
	}
	else
		this->EndModal(wxID_CANCEL);
}

IMPLEMENT_DYNAMIC_CLASS(ScriptEditor, wxButton)


void ScriptEditor::OnClick(wxMouseEvent &evt)
{
	dialog = new ScriptEditorDialog(this, wxID_ANY, scriptString);

	wxString scriptTmp = scriptString;

	if (dialog->ShowModal() == wxID_OK)
		scriptTmp = dialog->GetScript();

	if (scriptTmp != scriptString)
	{
		SetValue(scriptTmp);
		SendEvent();
	}

	SAFE_DELETE(dialog);
}

void ScriptEditor::SendEvent()
{
	wxCommandEvent textEvent(wxEVT_COMMAND_TEXT_ENTER, this->GetId());

	textEvent.SetEventObject(this);
	textEvent.SetClientData(&scriptString);
	textEvent.SetString(scriptString);

	this->ProcessEvent(textEvent);
}

void ScriptEditor::SetValue(const wxString &value)
{
	if (value == scriptString)
		return;

	scriptString = value;

	this->SetLabel(scriptString.IsEmpty() ? wxT("none") : wxT("edit"));
}


// Register with wxWidgets' dynamic class subsystem.
IMPLEMENT_DYNAMIC_CLASS(ScriptEditorXmlHandler, wxXmlResourceHandler)
