########################################################################
#	Hello Worlds - Libre 3D RPG game.
#	Copyright (C) 2020  CYBERDEViL
#
#	This file is part of Hello Worlds.
#
#	Hello Worlds is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#
#	Hello Worlds 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 General Public License for more details.
#
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
########################################################################


from panda3d.core import CollisionNode, CollisionTraverser, GeomNode
from panda3d.core import CollisionHandlerQueue, CollisionRay
from direct.showbase import DirectObject

class WorldMouse(DirectObject.DirectObject):
	def __init__(self, node):
		self._node = node

		self.myHandler = CollisionHandlerQueue()
		self.myTraverser = CollisionTraverser('mouseTraverser') # picker

		self.pickerNode = CollisionNode('mouseRay')
		self.pickerNP = camera.attachNewNode(self.pickerNode)
		self.pickerNode.setFromCollideMask(GeomNode.getDefaultCollideMask())
		self.pickerRay = CollisionRay()
		self.pickerNode.addSolid(self.pickerRay)
		self.myTraverser.addCollider(self.pickerNP, self.myHandler)

		self._hoverObjs = []

	def getClosest(self):
		mpos = base.mouseWatcherNode.getMouse()
		self.pickerRay.setFromLens(base.camNode, mpos.getX(), mpos.getY())

		self.myTraverser.traverse(render)
		if self.myHandler.getNumEntries() > 0:
			self.myHandler.sortEntries() # Sort so the closest object is at index 0
			pickedObj = self.myHandler.getEntry(0).getIntoNodePath()

			return pickedObj
		return None


class NPCMouse(WorldMouse):
	def __init__(self, node, model):
		WorldMouse.__init__(self, node)
		self._selectModel = model
		base.mouseHandler.connect('mouse1', self.onClick, priority=9)

	@property
	def selectModel(self): return self._selectModel

	def onClick(self):
		pickedObj = self.getClosest()
		if pickedObj:
			pickedObjTag = pickedObj.findNetTag('npcId')
			if not pickedObjTag.isEmpty():
				self._selectModel.selectedId = int(pickedObjTag.getTag('spawnId'))
				return True

		self._selectModel.selectedId = -1
		return False
