#include <psemek/ui/event_interceptor.hpp>
#include <psemek/ui/null_shape.hpp>

namespace psemek::ui
{

	math::box<float, 2> event_interceptor::size_constraints() const
	{
		if (child_)
			return child_->size_constraints();
		return element::size_constraints();
	}

	math::interval<float> event_interceptor::width_constraints(float height) const
	{
		if (child_)
			return child_->width_constraints(height);
		return element::width_constraints(height);
	}

	math::interval<float> event_interceptor::height_constraints(float width) const
	{
		if (child_)
			return child_->height_constraints(width);
		return element::height_constraints(width);
	}

	shape const & event_interceptor::shape() const
	{
		static const null_shape fallback_shape;
		if (child_)
			return child_->shape();
		return fallback_shape;
	}

	void event_interceptor::reshape(math::box<float, 2> const & bbox)
	{
		if (child_)
			child_->reshape(bbox);
	}

	void event_interceptor::on_mouse_move(std::function<bool(mouse_move const &)> callback)
	{
		mouse_move_callback_ = std::move(callback);
	}

	void event_interceptor::on_mouse_click(std::function<bool(mouse_click const &)> callback)
	{
		mouse_click_callback_ = std::move(callback);
	}

	void event_interceptor::on_mouse_wheel(std::function<bool(mouse_wheel const &)> callback)
	{
		mouse_wheel_callback_ = std::move(callback);
	}

	void event_interceptor::on_key_press(std::function<bool(key_press const &)> callback)
	{
		key_press_callback_ = std::move(callback);
	}

	void event_interceptor::on_update(std::function<void(float)> callback)
	{
		update_callback_ = std::move(callback);
	}

	bool event_interceptor::on_event(mouse_move  const & event)
	{
		if (child_)
			mouseover_ = child_->shape().contains(math::cast<float>(event.position));
		else
			mouseover_ = false;

		if (mouseover_ && mouse_move_callback_)
			return mouse_move_callback_(event);
		return false;
	}

	bool event_interceptor::on_event(mouse_click const & event)
	{
		if (mouseover_ && mouse_click_callback_)
			return mouse_click_callback_(event);
		return false;
	}

	bool event_interceptor::on_event(mouse_wheel const & event)
	{
		if (mouseover_ && mouse_wheel_callback_)
			return mouse_wheel_callback_(event);
		return false;
	}

	bool event_interceptor::on_event(key_press   const & event)
	{
		if (key_press_callback_)
			return key_press_callback_(event);
		return false;
	}

	void event_interceptor::update(float dt)
	{
		if (update_callback_)
			update_callback_(dt);
	}

}
