# Hurry Curry! - a game about cooking
# Copyright (C) 2026 Hurry Curry! Contributors
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, version 3 of the License only.
#
# This program 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
extends Control
class_name PopupMessage

const SERVER_MESSAGE_SCENE = preload("res://gui/overlays/popup_message/server_message.tscn")

var positional_messages = {}

@onready var positional_messages_node: Control = $Positional
@onready var server_msg = $Static/VBox/ServerMessage
@onready var server_hint = $Static/VBox/ServerHint
@onready var server_msg_timer: Timer = $ServerMessage

@onready var game: Game = $"../../Game" # TODO

func _process(_delta: float):
	for pos: Vector2 in positional_messages.keys():
		var camera: Camera3D = get_viewport().get_camera_3d()
		var msg: PositionalMessage = positional_messages[pos]
		var pos_3d = Vector3(pos.x + 0.5, 1.5, pos.y + 0.5)
		var pos_2d = camera.unproject_position(pos_3d)
		var behind = camera.is_position_behind(pos_3d)

		msg.node_2d.visible = not behind
		msg.node_2d.position = pos_2d.clamp(
			Vector2.ZERO + 0.5 * msg.node.size,
			Vector2(get_viewport_rect().size) - 0.5 * msg.node.size
		)
		
		if msg.node.size != msg.last_size:
			msg.last_size = msg.node.size
			msg.node.position = -0.5 * msg.last_size

func display_server_hint(msg):
	server_hint.show()
	server_hint.set_text(msg)

func display_server_msg(msg, auto_remove := true):
	server_msg.show()
	server_msg.set_text(msg)
	if auto_remove:
		server_msg_timer.start()

func _on_server_timeout() -> void:
	clear_server_msg()

func display_server_hint_positional(text, pos: Vector2, use_monospace: bool):
	var msg := PositionalMessage.new()
	msg.node = SERVER_MESSAGE_SCENE.instantiate()
	msg.node_2d = Node2D.new()
	positional_messages_node.add_child(msg.node_2d)
	msg.node_2d.add_child(msg.node)
	msg.node.set_text(text, use_monospace)
	msg.node.size = Vector2.ZERO
	msg.position = pos
	positional_messages[pos] = msg

func clear_server_msg():
	server_msg_timer.stop()
	server_msg.hide()

func clear_server_hint(position_ = null):
	if position_ == null:
		server_hint.hide()
	else:
		if position_ in positional_messages:
			var msg: PositionalMessage = positional_messages[position_]
			msg.node_2d.queue_free()
			positional_messages.erase(position_)

class PositionalMessage:
	var node: ServerMessage
	var node_2d: Node2D
	var position: Vector2
	var last_size: Vector2
