extends "res://lib/core/dialogue/text_box.gd"
# Framed dialogue only. The original parser, text array, pause/reveal tweens,
# options, close/input signals and actor state remain inherited.
const DIALOGUE_ROWS = 3
var _zhtw_frame = null
var _zhtw_sizing = false
var _zhtw_overhead = 21

func _ready():
	var possible = get_parent().get_parent().get_parent().get_parent()
	if possible != null and possible.get_filename().replace(".tscn.converted.scn", ".tscn") == "res://lib/core/dialogue/dialogue_box.tscn" and str(possible.get_path_to(self)) == "HBox/Control/Text Panel/Text Box":
		_zhtw_frame = possible
		_frame_height(DIALOGUE_ROWS)
	._ready()

func _frame_height(rows):
	if _zhtw_frame == null or _zhtw_sizing:
		return
	_zhtw_sizing = true
	var header = _zhtw_frame.get_node("Header Panel")
	var panel_top = 11
	if not header.is_hidden():
		panel_top = max(panel_top, header.get_combined_minimum_size().y - 7)
	# Body starts eight pixels below the Text Panel. Keep the original one
	# pixel gap after the actual name panel, including its private CJK font.
	_zhtw_overhead = panel_top + 10
	var height = _zhtw_overhead + max(DIALOGUE_ROWS, rows) * font.get_height()
	var previous_height = _zhtw_frame.get_size().y
	var previous_pos = _zhtw_frame.get_pos()
	_zhtw_frame.set_custom_minimum_size(Vector2(320, height))
	_zhtw_frame.set_size(Vector2(_zhtw_frame.get_size().x, height))
	# Preserve the native frame's vertical alignment if a future caller sets it.
	if _zhtw_frame.get_anchor(MARGIN_TOP) == ANCHOR_END and _zhtw_frame.get_anchor(MARGIN_BOTTOM) == ANCHOR_END:
		_zhtw_frame.set_pos(previous_pos - Vector2(0, height - previous_height))
	elif _zhtw_frame.get_anchor(MARGIN_TOP) == ANCHOR_CENTER and _zhtw_frame.get_anchor(MARGIN_BOTTOM) == ANCHOR_CENTER:
		_zhtw_frame.set_pos(previous_pos - Vector2(0, (height - previous_height) / 2))
	var hbox = _zhtw_frame.get_node("HBox")
	var control = _zhtw_frame.get_node("HBox/Control")
	var fixed_width = 0.0
	var visible_count = 0
	for child in hbox.get_children():
		if child.is_hidden():
			continue
		visible_count += 1
		if child != control:
			fixed_width += child.get_custom_minimum_size().x
	var control_width = _zhtw_frame.get_size().x - fixed_width - max(0, visible_count - 1) * hbox.get_constant("separation")
	control.set_size(Vector2(control_width, height))
	hbox.set_size(Vector2(hbox.get_size().x, height))
	control.set_size(Vector2(control_width, height))
	get_parent().set_margin(MARGIN_TOP, panel_top)
	get_parent().set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, 0)
	set_size(Vector2(control_width - 16, height - _zhtw_overhead))
	_zhtw_sizing = false

func update_max_lines():
	.update_max_lines()
	if _zhtw_frame != null:
		# An indivisible long entry can grow the frame, but never combine it with
		# another entry on that page. Native input/reveal progression is unchanged.
		max_lines = DIALOGUE_ROWS
		while get_child_count() > max_lines:
			get_child(get_child_count() - 1).free()

func close():
	.close()
	if _zhtw_frame != null:
		_frame_height(DIALOGUE_ROWS)

func clear_lines():
	.clear_lines()
	if _zhtw_frame != null:
		_frame_height(DIALOGUE_ROWS)

func _rendered_lines(label):
	var effect = label.get_node("SpecialEffectLabel")
	if not effect.is_effectively_empty():
		effect.get_total_character_count()
		return max(1, effect.get_line_count())
	var rich = label.get_node("RichTextLabel")
	if rich.get_text().length() > 0:
		# Godot 2.1 RichTextLabel has no line-count API. Its plain text is
		# measured with the same private body font and final content width.
		var measure = Label.new()
		measure.hide()
		get_tree().get_root().add_child(measure)
		measure.add_font_override("font", font)
		measure.add_constant_override("line_spacing", 0)
		measure.set_autowrap(true)
		measure.set_size(Vector2(label.get_size().x, 1))
		measure.set_text(rich.get_text())
		var count = measure.get_line_count()
		measure.free()
		return max(1, count)
	return max(1, label.get_line_count())

func _prepare_line(idx = text_idx):
	if _zhtw_frame == null:
		._prepare_line(idx)
		return
	if idx >= text.size():
		clear_next = true
		return
	if text[idx] == "":
		text_idx += 1
		clear_next = true
		return
	_frame_height(max(DIALOGUE_ROWS, int((_zhtw_frame.get_size().y - _zhtw_overhead) / font.get_height())))
	var available_lines = DIALOGUE_ROWS
	working_node = null
	var previous_entry = null
	var previous_lines = 0
	for entry in get_children():
		if entry.is_hidden():
			working_node = entry.get_node("Label")
			break
		previous_lines = _rendered_lines(entry.get_node("Label"))
		available_lines -= previous_lines
		previous_entry = entry
	if working_node == null:
		clear_next = true
		return
	# Set the real final width before parsing; SE caches wrap boundaries and
	# pause positions. Include native HBox spacing as well as bullet/indent.
	var width = get_size().x
	var entry = working_node.get_parent()
	var visible_prefixes = 0
	for path in ["bullet", "Indent"]:
		if not entry.get_node(path).is_hidden():
			width -= entry.get_node(path).get_size().x
			visible_prefixes += 1
	width -= visible_prefixes * entry.get_constant("separation")
	working_node.set_size(Vector2(width, working_node.get_size().y))
	_parse_text(_dialogue_display_markup(text[idx]))
	working_node.get_node("RichTextLabel").add_font_override("normal_font", font)
	working_node.set_percent_visible(1)
	var lines = _rendered_lines(working_node)
	working_node.set_custom_minimum_size(Vector2(0, lines * font.get_height()))
	if lines > available_lines and available_lines < DIALOGUE_ROWS:
		clear_next = true
		return
	_frame_height(max(DIALOGUE_ROWS, DIALOGUE_ROWS - available_lines + lines))
	entry.set_stretch_ratio(max(1, available_lines))
	if previous_entry != null:
		previous_entry.set_stretch_ratio(previous_lines)


func _dialogue_display_markup(value):
	# Two complete compiled display values contain malformed native tags.
	# Preserve cutscene data, IDs, sequence text and all other markup verbatim.
	if value == "靠近點，[.][c=gold]魯特[c=white[.[.]":
		return "靠近點，[.][c=gold]魯特[c=white][.][.]"
	if value == "[c=t=.7]弟兄們，上啊！！[.]":
		return "[t=.7]弟兄們，上啊！！[.]"
	return value
