#include "StdAfx.h"
#include "FormVertexBuilder.h"

#include <LibQtGeoViewerCore/GeomObject.h>
using namespace geom;



FormVertexBuilder::FormVertexBuilder(QWidget *parent)
	: QDialog(parent)
{
	ui.setupUi(this);

	Qt::WindowFlags flags = windowFlags() & (~Qt::WindowContextHelpButtonHint);
	flags = flags | Qt::WindowMinimizeButtonHint;
	flags = flags | Qt::WindowCloseButtonHint;
	setWindowFlags(flags);
}

FormVertexBuilder::~FormVertexBuilder()
{
}

void FormVertexBuilder::keyPressEvent(QKeyEvent *e)
{
	bool Alt   = ( ( e->modifiers() & Qt::AltModifier     ) != 0 );
	bool Shift = ( ( e->modifiers() & Qt::ShiftModifier   ) != 0 );
	bool Ctrl  = ( ( e->modifiers() & Qt::ControlModifier ) != 0 );

	if(e->key() == Qt::Key_Escape)
	{
		close();
		return;
	}

	if(Ctrl && !Shift && !Alt)
	{
		if(e->key() == Qt::Key_Q)
		{
			close();
			return;
		}
	}
}

void FormVertexBuilder::on_buttonBox_accepted()
{
	accept();
}

void FormVertexBuilder::on_buttonBox_rejected()
{
	reject();
}

void FormVertexBuilder::on_pushClear_clicked()
{
	ui.plainTextEdit->clear();
}


void FormVertexBuilder::CreateVertex(SceneMain& scene)
{
	if(exec() != QDialog::Accepted)
		return;

	QString s = ui.plainTextEdit->document()->toPlainText();
	QStringList sl = s.split("\n");

	std::vector<lm::vec3f> verts;
	for(int i = 0; i < sl.size(); ++i)
	{
		const QString& l = sl[i];
		QRegExp vx("x\\s*=\\s*(-?[0-9]+(\\.[0-9]*)?)");
		QRegExp vy("y\\s*=\\s*(-?[0-9]+(\\.[0-9]*)?)");
		QRegExp vz("z\\s*=\\s*(-?[0-9]+(\\.[0-9]*)?)");

		lm::vec3f v(0.0f, 0.0f, 0.0f);
		bool match = false;
		if(vx.indexIn(l) != -1)
		{
			v.x = vx.cap(1).toFloat();
			match = true;
		}

		if(vy.indexIn(l) != -1)
		{
			v.y = vy.cap(1).toFloat();
			match = true;
		}

		if(vz.indexIn(l) != -1)
		{
			v.z = vz.cap(1).toFloat();
			match = true;
		}

		if(!match)
			continue;

		verts.push_back(v);
	}

	if(verts.empty())
		return;

	GeomObject* obj = new GeomObject();
	scene.AddObject(obj);

	obj->m_Mesh.m_Verts.swap(verts);
	obj->m_Name = "vertscript";
	obj->UpdateBBox();
	obj->m_VertexOnlyMode = true;

	if(ui.radioLoop->isChecked() || ui.radioStrip->isChecked())
	{
		VertexLinker linker;

		for(size_t i = 0; i < obj->m_Mesh.m_Verts.size(); ++i)
		{
			linker.m_VertLinks.push_back((int)i);
		}

		if(ui.radioLoop->isChecked())
			linker.m_IsLoop = true;

		obj->m_VertLinkers.push_back(linker);
	}

	scene.UpdateTransform();

	scene.ReportDoneEditGeometry();
}
