import bge

def finished_cb(status):
	print("Library (%s) loaded in %.2fms." % (status.libraryName, status.timeTaken))    


def main(cont):
	own = cont.owner
	sens = cont.sensors['Collision']

	if sens.positive:
		mainDir = bge.logic.expandPath("//")
		wLib = mainDir + "assets\\" + own['libName'] 
		print('colliding') 
		to_free = None

		if own['libName'] not in str(bge.logic.LibList()):
			print(wLib, 'loading')
			#bge.logic.LibLoad(wLib, 'Scene', asynchronous=True).onFinish = finished_cb
			bge.logic.LibLoad(wLib, 'Scene', async=True).onFinish = finished_cb
		else:
			y = bge.logic.LibList()
			for x in y:
				if own['libName'] in x:
					print('unloading', x)
					to_free = x
					#bge.logic.LibFree(x)
		if to_free != None:
			bge.logic.LibFree(to_free)			
				#else:
					#print('cant unload', x, y)	
			#print('not loading', bge.logic.LibList(), wLib)
				