# Hurry Curry! - a game about cooking
# Copyright (C) 2025 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 PinnedItemMessages

const ITEM_MESSAGE_SCENE := preload("res://gui/components/message/item/item_message.tscn")
const PAPER_PANEL_STYLE := preload("res://gui/resources/style/paper_panel_style.tres")

var pinned_items := {}

@onready var pinned_items_container: HBoxContainer = $HBoxContainer

func pin_item(item_name: String, timeout_initial_: float, timeout_remaining_: float, player_id: float):
	var item_message: ItemMessage = ITEM_MESSAGE_SCENE.instantiate()
	item_message.remove_theme_stylebox_override("panel")
	item_message.enable_rotation = false
	item_message.enable_grayscale = true
	item_message.add_theme_stylebox_override("panel", PAPER_PANEL_STYLE)
	pinned_items_container.add_child(item_message)
	item_message.set_subviewport_size(Vector2(96, 84))
	item_message.set_round_corner_radius_progress(0)
	item_message.set_item(item_name, timeout_initial_, timeout_remaining_)
	pinned_items[player_id] = item_message
	sort_pins()

func clear_item(player_id: float):
	if player_id in pinned_items:
		if is_instance_valid(pinned_items[player_id]):
			pinned_items[player_id].queue_free()

func sort_pins():
	var sorted_nodes := pinned_items_container.get_children()
	
	sorted_nodes.sort_custom(
		func(a: Node, b: Node): return a.timeout_remaining < b.timeout_remaining
	)
	
	for node in pinned_items_container.get_children():
		pinned_items_container.remove_child(node)
	
	for node in sorted_nodes:
		pinned_items_container.add_child(node)
