#include "PlaceCircleTool.h"

void PlaceCircleTool::InstallNewInstance()
{
	PlaceCircleTool* newTool = new PlaceCircleTool();
	newTool->InstallTool();
}

BentleyStatus PlaceCircleTool::CreateCircle(EditElementHandleR eehCirc, DPoint3d const &ptCircCenter)
{
	
	double radius = mdlModelRef_getUorPerMeter(ACTIVEMODEL);
	DEllipse3d elli = DEllipse3d::FromCenterRadiusXY(ptCircCenter, radius);
	ICurvePrimitivePtr cvePri = ICurvePrimitive::CreateArc(elli);
	if(SUCCESS!=DraftingElementSchema::ToElement(eehCirc, *cvePri, NULL, true, *ACTIVEMODEL))
	{
		return ERROR;
	}
	RotMatrix rMatrix;
	mdlRMatrix_fromView(&rMatrix, IViewManager::GetManager().GetCurrentViewNumber(), false);
	mdlRMatrix_invert(&rMatrix, &rMatrix);
	Transform transform = Transform::FromMatrixAndFixedPoint(rMatrix, ptCircCenter);
	TransformInfo transformInfo = TransformInfo(transform);
	eehCirc.GetDisplayHandler()->ApplyTransform(eehCirc, transformInfo);
	return SUCCESS;
}

PlaceCircleTool::PlaceCircleTool():DgnPrimitiveTool(0,0)
{

}

void PlaceCircleTool::_OnPostInstall()
{
		_BeginDynamics();
}

bool PlaceCircleTool::_OnDataButton(DgnButtonEventCR ev)
{
	EditElementHandle eehCirc;
	if (SUCCESS == CreateCircle(eehCirc, *ev.GetPoint()))
	{
		eehCirc.AddToModel();
	}
	return false;
}

bool PlaceCircleTool::_OnResetButton(DgnButtonEventCR ev)
{
	_OnReinitialize();
	return false;
}

void PlaceCircleTool::_OnDynamicFrame(DgnButtonEventCR ev)
{
	EditElementHandle eehCirc;
	if (SUCCESS == CreateCircle(eehCirc, *ev.GetPoint()))
	{
		RedrawElems     redrawElems;
		redrawElems.SetDynamicsViews(IViewManager::GetActiveViewSet(), ev.GetViewport());
		redrawElems.SetDrawMode(DRAW_MODE_TempDraw);
		redrawElems.SetDrawPurpose(DrawPurpose::Dynamics);
		redrawElems.DoRedraw(eehCirc);
	}
}

void PlaceCircleTool::_OnRestartTool()
{
	InstallNewInstance();
}
