/********************************************************************/
/* Copyright (c) 2019 System fugen G.K. and Yuzi Mizuno          */
/* All rights reserved.                                             */
/* ***************************************************** */
/********************************************************************/
// mgjoin.cpp
// implementation for functions about join operation
#include "stdafx.h"

#include "Calc/mgjoin.h"
#include "mg/Plane.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

namespace mgcalc{
	/// Makes a composite curve connect obj2 at its endpoint.
	/// Returns true if succeeds.
	bool join(MGCompositeCurve* compo, const MGCurve* c){
		if(!compo || !c) return false;

		MGPosition s = c->start_point(), e = c->end_point();
		MGPosition pos = compo->end_point();
		if(pos == s || pos == e){
			compo->connect_to_end(c->clone());
			return true;
		}else{
			pos = compo->start_point();
			if(pos == s || pos == e){
				compo->connect_to_start(c->clone());
				return true;
			}else{
				return false;
			}
		}
	}

	/// Returns join(MGCompositeCurve*, const MGCurve*) if obj is curve.
	bool join(MGCompositeCurve* compo, const MGObject* obj){
		const MGCurve* c = dynamic_cast<const MGCurve*>(obj);
		if(c)
			return join(compo, c);
		return false;
	}

	// Join obj2 to obj, which obj2 is required to be face or surface.
	bool join(MGShell* shel, const MGObject* obj2){
		const MGFace* f = dynamic_cast<const MGFace*>(obj2);
		if(f)
			return join(shel, f);

		const MGSurface* srf = dynamic_cast<const MGSurface*>(obj2);
		if(srf)
			return join(shel, srf);
		return false;
	}

	// Join obj2 to obj. (dispatcher function)
	bool join(MGObject* obj, const MGObject* obj2){
		MGShell* she = dynamic_cast<MGShell*>(obj);
		if(she)
			return join(she, obj2);

		MGCompositeCurve* compo = dynamic_cast<MGCompositeCurve*>(obj);
		if(compo)
			return join(compo, obj2);
		
		return false;
	}

	// Creates a kernel object of a composite object.
	MGObject* join_seed(const MGObject& obj){
		// 1. composite curve
		const MGCompositeCurve* compo = dynamic_cast<const MGCompositeCurve*>(&obj);
		if(compo)
			return compo->clone();

		const MGCurve* c = dynamic_cast<const MGCurve*>(&obj);
		if(c)
			return new MGCompositeCurve(c->clone());
		
		// 2. shell
		const MGShell* she = dynamic_cast<const MGShell*>(&obj);
		if(she)
			return she->clone();

		const MGFace* f = dynamic_cast<const MGFace*>(&obj);
		if(f)
			return new MGShell(*f);

		const MGPlane* pl = dynamic_cast<const MGPlane*>(&obj);
		if(pl)
			return 0;

		const MGSurface* srf = dynamic_cast<const MGSurface*>(&obj);
		if(srf)
			return new MGShell(*srf);
		return 0;
	}
}

