# 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 BlurSetup
class_name ServerMessage

const DEFAULT_FONT = preload("res://gui/resources/fonts/font-josefin-sans.woff2")
const MONOSPACE_FONT = preload("res://gui/resources/fonts/font-azaret-mono.woff2")
const RENDERER = preload("res://gui/components/message/renderer.tscn")

@onready var flow: VFlowContainer = $CenterContainer/VFlowContainer

func set_text(text, use_monospace := true):
	for c: Node in flow.get_children():
		c.queue_free()
	if text is String:
		flow.add_child(build_label(text, use_monospace))
	elif text is Array:
		for e: MessageParser in text:
			var c: Control = build_message(e, use_monospace)
			c.size_flags_horizontal = Control.SIZE_SHRINK_BEGIN
			c.size_flags_vertical = Control.SIZE_EXPAND_FILL
			flow.add_child(c)

static func font_size(use_monospace: bool):
	return 16 if use_monospace else 20

func build_label(text: String, use_monospace: bool) -> Label:
	var label = Label.new()
	var font: FontVariation = preload("res://gui/overlays/popup_message/font_variation.tres")
	var sb := StyleBoxEmpty.new()
	font.base_font = MONOSPACE_FONT if use_monospace else DEFAULT_FONT
	label.add_theme_font_size_override("font_size", font_size(use_monospace))
	label.add_theme_font_override("font", font)
	label.add_theme_color_override("font_color", Color.BLACK)
	label.add_theme_stylebox_override("normal", sb)
	label.autowrap_mode = TextServer.AUTOWRAP_OFF
	label.text = text
	label.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
	label.update_minimum_size()
	return label

func build_message(m: MessageParser, use_monospace: bool) -> Control:
	match m.kind:
		MessageParser.Kind.ITEM:
			var r: Renderer = RENDERER.instantiate()
			r.get_node("SubViewport").size = Vector2i.ONE * font_size(use_monospace) * 2
			r.setup_item(m.result)
			return r
		MessageParser.Kind.TILE:
			var r: Renderer = RENDERER.instantiate()
			r.get_node("SubViewport").size = Vector2i.ONE * font_size(use_monospace) * 2
			r.setup_tile([m.result])
			return r
		MessageParser.Kind.TEXT:
			return build_label(m.result, use_monospace)
	return null
