#-------------------------------------------------------------------------------
# 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
#-------------------------------------------------------------------------------


import os, os.path
import jpype
from Struct import Struct


def newFile( *pathParts ):
	return f.java.io.File( os.path.join( *pathParts ) )


def toArrayList( list ):
	arrayList = f.java.util.ArrayList( len( list ) )
	arrayList.addAll( list );
	return arrayList


class Jvm:
	
	def __init__( self ):
		
		self.__classpath = []
		self.__startupHandlers = []
		
		
	def addPath( self, path ):
		self.__classpath.append( path )
	
	
	def addLibsDir( self, libdir ):
		for file in os.listdir( libdir ):
			self.addPath( os.path.join( libdir + "/" + file ) )


	def getClasspath( self ):
		# on windows, the classpath separator is ; instead of :
		if os.name == "nt":
			separator = ";"
		else:
			separator = ":"
		return separator.join( self.__classpath )
	
	
	def addStartupHandler( self, handler ):
		self.__startupHandlers.append( handler )


	def start( self, flags="", debugAddress=None ):
		
		if debugAddress is not None:
			flags = "-agentlib:jdwp=transport=dt_socket,server=n,address=%d %s" % ( debugAddress, flags )
		
		jpype.startJVM(
			jpype.getDefaultJVMPath(),
			"-ea",
			"-Djava.class.path=%s" % self.getClasspath(),
			flags
		)
		
		# set up class factories
		global f; f = Struct()
		f.java = jpype.JPackage( "java" )
		f.javax = jpype.JPackage( "javax" )
		
		# send jvm startup events
		[handler( self ) for handler in self.__startupHandlers]
	
	
	def shutdown( self ):
		jpype.shutdownJVM()
	
	
	def attachThread( self ):
		jpype.attachThreadToJVM()

