extends Node
# Godot 2.1. Additional autoload, after ZhTWLocalization.
# Exact title instances only. Original resources, signals, focus and input stay intact.

const TITLE_SCENE = "res://lib/ui/title_menu/@TITLE.tscn"
const FONT_PATH = "res://lib/ui/fonts/BOLD.tres"
const FALLBACK_PATH = "res://localization/zh-TW/fonts/cjk-ui-pixel-v0.1/font.tres"
var buttons = []
var font = null
var tree_dirty = false
var entries = {
	"Buttons/New Game Button": ["開始遊戲", "newgame_grey.png"],
	"Buttons/Load Game Button": ["讀取遊戲", "Loadgame_grey.png"],
	"Buttons/Settings Button": ["設定", "settings_gray.png"],
	"Buttons/Quit Game": ["離開遊戲", "quite_game_gray.png"]
}

func _ready():
	font = _font()
	if font == null:
		print("KOTD_TITLE_FONT_MISSING")
		return

func _font():
	if has_node("/root/ZhTWLocalization"):
		var cache = get_node("/root/ZhTWLocalization").get("font_overrides")
		if typeof(cache) == TYPE_DICTIONARY and cache.has(FONT_PATH):
			return cache[FONT_PATH]
	var original = load(FONT_PATH)
	var fallback = load(FALLBACK_PATH)
	if original == null or fallback == null:
		return null
	var copy = original.duplicate()
	copy.set("fallback", fallback)
	copy.set("height", 13)
	copy.set("ascent", 10)
	return copy

func _canonical(path):
	return path.replace(".tscn.converted.scn", ".tscn")

func _label(text):
	var label = Label.new()
	label.set_name("ZhTWText")
	label.set_text(text)
	label.add_font_override("font", font)
	label.set_ignore_mouse(true)
	label.set_stop_mouse(false)
	label.set_focus_mode(0)
	label.set_align(1)
	label.set_valign(1)
	label.set_autowrap(false)
	label.set_clip_text(false)
	return label

func _install(reference):
	var root = reference.get_ref()
	if root == null or root.has_meta("zhtw_title_installed"):
		return
	# Check the complete source boundary before altering any button.
	for path in entries:
		if not root.has_node(path):
			return
		var button = root.get_node(path)
		if not button.is_type("TextureButton"):
			return
		var texture = button.get_normal_texture()
		if texture == null or texture.get_path() != "res://lib/ui/title_menu/" + entries[path][1]:
			return
	root.set_meta("zhtw_title_installed", true)
	for path in entries:
		var button = root.get_node(path)
		var size = button.get_size()
		var minimum = button.get_combined_minimum_size()
		var prior = [button.get_normal_texture(), button.get_pressed_texture(), button.get_hover_texture(), button.get_disabled_texture(), button.get_focused_texture()]
		button.set_meta("zhtw_original_textures", prior)
		button.set_meta("zhtw_original_custom_minimum", button.get_custom_minimum_size())
		button.set_custom_minimum_size(minimum)
		button.set_normal_texture(null)
		button.set_pressed_texture(null)
		button.set_hover_texture(null)
		button.set_disabled_texture(null)
		button.set_focused_texture(null)
		button.set_size(size)
		var label = _label(entries[path][0])
		button.add_child(label)
		_watch_button(button, {"button": weakref(button), "label": weakref(label)})
	# The logo artwork remains untouched. This fits the gap above the first option.
	var subtitle = _label("垃圾王國")
	subtitle.set_name("ZhTWSubtitle")
	subtitle.add_color_override("font_color", Color(1.0, 0.83, 0.44, 1.0))
	var subtitle_parent = root
	if root.has_node("FULL COLOR"):
		subtitle_parent = root.get_node("FULL COLOR")
	subtitle_parent.add_child(subtitle)
	subtitle.set_pos(Vector2(160, 144))
	subtitle.set_size(Vector2(108, 13))


func _connect_event(node, signal_name, method0, method1, reference):
	for info in node.get_signal_list():
		if info["name"] != signal_name:
			continue
		var argc = info["args"].size()
		var method = method0 if argc == 0 else method1
		if argc > 1:
			return
		if not node.is_connected(signal_name, self, method):
			node.connect(signal_name, self, method, [reference])
		return

func register_owner(owner, expected_scene):
	if owner != null and expected_scene == TITLE_SCENE and _canonical(owner.get_filename()) == TITLE_SCENE:
		_install(weakref(owner))

func _watch_button(button, item):
	button.set_meta("zhtw_v35_title_item", item)
	for signal_name in ["draw", "item_rect_changed", "visibility_changed", "focus_enter", "focus_exit", "mouse_enter", "mouse_exit", "pressed", "released", "toggled"]:
		_connect_event(button, signal_name, "_title_event", "_title_event_arg", weakref(button))
	_title_event(weakref(button))

func _title_event_arg(value, reference):
	_title_event(reference)

func _title_event(reference):
	var button = reference.get_ref()
	if button == null or button.has_meta("zhtw_v35_title_queued"):
		return
	button.set_meta("zhtw_v35_title_queued", true)
	call_deferred("_title_apply", reference)

func _title_apply(reference):
	var button = reference.get_ref()
	if button == null:
		return
	button.set_meta("zhtw_v35_title_queued", null)
	var item = button.get_meta("zhtw_v35_title_item")
	var label = item["label"].get_ref()
	if label == null:
		return
	var size = button.get_size()
	var signature = str([size, button.is_disabled(), button.get_draw_mode(), button.has_focus()])
	if button.has_meta("zhtw_v35_title_result") and button.get_meta("zhtw_v35_title_result") == signature:
		return
	var pos = Vector2(0, floor((size.y - 13) / 2))
	if label.get_pos() != pos:
		label.set_pos(pos)
	var target_size = Vector2(size.x, 13)
	if label.get_size() != target_size:
		label.set_size(target_size)
	var color = Color(0.62, 0.62, 0.62, 1.0)
	if button.is_disabled():
		color = Color(0.37, 0.37, 0.37, 1.0)
	elif button.get_draw_mode() != 0 or button.has_focus():
		color = Color(1.0, 1.0, 1.0, 1.0)
	if label.get_color("font_color") != color:
		label.add_color_override("font_color", color)
	button.set_meta("zhtw_v35_title_result", signature)
