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

class MouseEventHandler:
	def __init__(self, eventName):
		self._eventName = eventName
		self._callbacks = {}

		base.accept(eventName, self.__event)

	def __event(self):
		# LUI goes for everything..
		if base.uiManager.hasMouse(): return

		for priority, callbackList in sorted(self._callbacks.items()):
			for callback in callbackList:
				if callback[0](*callback[1]):
					return # Callback accepted

	def addCallback(self, callback, args=[], priority=0):
		if priority not in self._callbacks:
			self._callbacks.update({ priority : [] })

		self._callbacks[priority].append([callback, args])

class MouseHandler:
	""" Note: callbacks must return True if they used the event and
		False when they don't.
	"""
	def __init__(self):
		self._eventHandlers = {
			'mouse1'	: MouseEventHandler('mouse1'),
			'mouse1-up'	: MouseEventHandler('mouse1-up'),

			'mouse3'	: MouseEventHandler('mouse3'),
			'mouse3-up'	: MouseEventHandler('mouse3-up'),

			'wheel_up'	: MouseEventHandler('wheel_up'),
			'wheel_down': MouseEventHandler('wheel_down')
		}

	def connect(self, eventName, callback, args=[], priority=0):
		self._eventHandlers[eventName].addCallback(callback, args=args, priority=priority)

	def showCursor(self, state=True):
		wprops = WindowProperties()
		wprops.setCursorHidden(not state)
		base.win.requestProperties(wprops)

	def cursorVisible(self):
		return not WindowProperties().getCursorHidden()
