/*******************************************************************************
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA
 * 
 * Contact Info:
 * 	Bruce Donald
 * 	Duke University
 * 	Department of Computer Science
 * 	Levine Science Research Center (LSRC)
 * 	Durham
 * 	NC 27708-0129 
 * 	USA
 * 	brd@cs.duke.edu
 * 
 * Copyright (C) 2011 Jeffrey W. Martin and Bruce R. Donald
 * 
 * <signature of Bruce Donald>, April 2011
 * Bruce Donald, Professor of Computer Science
 ******************************************************************************/


#include <jni.h>

#include "cgal.h"
#include "shotCgal.h"
#include "global.h"
#include "types.h"
#include "Storage.h"


#define CLASS				Java_edu_duke_donaldLab_jdshot_disco_cgal_Vertex
#define Vertex_cleanup		CLASSFN( CLASS, cleanup )
#define Vertex_equals		CLASSFN( CLASS, equals )
#define Vertex_toPoint		CLASSFN( CLASS, toPoint )


typedef std::pair<int,Arrangement::Vertex> VertexMapPair;


static Storage<Arrangement::Vertex> g_vertices( CGALCLASS( "Vertex" ), false );


void verticesCleanup( JNIEnv *jvm )
{
	g_vertices.cleanupAll( jvm );
}

Arrangement::Vertex *getVertex( JNIEnv *jvm, jobject self )
{
	return g_vertices.get( jvm, self );
}

jobject newVertex( JNIEnv *jvm, Arrangement::Vertex *pVertex )
{
	return g_vertices.addNew( jvm, pVertex );
}


JNIEXPORT void JNICALL Vertex_cleanup( JNIEnv *jvm, jclass c, jint id )
{
	START_SIGNAL_HANDLING
	{
		if( !g_vertices.cleanup( id ) )
		{
			throwException( jvm, "Vertex cleanup failure!" );
		}
	}
	STOP_SIGNAL_HANDLING
}

JNIEXPORT jboolean JNICALL Vertex_equals( JNIEnv *jvm, jobject self, jobject other )
{
	START_SIGNAL_HANDLING
	{
		// check arguments
		if( other == NULL )
		{
			throwIllegalArgumentException( jvm, "other must not be null." );
		}

		return getVertex( jvm, self )->point() == getVertex( jvm, other )->point();
	}
	STOP_SIGNAL_HANDLING
	return false;
}

JNIEXPORT jobject JNICALL Vertex_toPoint( JNIEnv *jvm, jobject self )
{
	START_SIGNAL_HANDLING
	{
		Arrangement::Vertex *pVertex = getVertex( jvm, self );
		return newVector2(
			jvm,
			to_double( pVertex->point().x() ),
			to_double( pVertex->point().y() )
		);
	}
	STOP_SIGNAL_HANDLING
	return NULL;
}
