@tool
extends EditorPlugin


var dialogue_highlighter:DialogueHighlighter


func _enter_tree() -> void:
	dialogue_highlighter = DialogueHighlighter.new()
	var script_editor = EditorInterface.get_script_editor()
	print(script_editor)
	print(dialogue_highlighter)
	script_editor.register_syntax_highlighter(dialogue_highlighter)
	print(script_editor.get_current_script())
	print(script_editor.get_open_scripts())
	script_editor.goto_line(20)


func _exit_tree() -> void:
	if is_instance_valid(dialogue_highlighter):
		var script_editor = EditorInterface.get_script_editor()
		script_editor.unregister_syntax_highlighter(dialogue_highlighter)
		dialogue_highlighter = null


class DialogueHighlighter extends EditorSyntaxHighlighter:
	func _get_name() -> String:
		return "Laia"

	func _get_supported_languages() -> PackedStringArray:
		return ["TextFile"]

	func _get_line_syntax_highlighting(line: int) -> Dictionary:
		var color_map = {}
		var text_editor = get_text_edit()
		var str = text_editor.get_line(line)
		
		# Comment
		if str.strip_edges().begins_with("#"):
			color_map[0] = { "color": Color.WEB_GRAY }
			return color_map
		
		# Key
		var regex3 = RegEx.new()
		regex3.compile("([a-zA-Z0-9_]+:).*")
		var result3 = regex3.search(str)
		
		if result3:
			color_map[result3.get_start(1)] = { "color": Color.SEA_GREEN }
			color_map[result3.get_end(1)] = { "color": Color.WHITE }
		
		# Array
		var regex = RegEx.new()
		regex.compile("([a-zA-Z0-9_\\-])+\\[\\]")
		var result = regex.search(str)
		
		if result:
			color_map[result.get_start()] = { "color": Color.CYAN }
			color_map[result.get_end(1)] = { "color": Color.LIGHT_CYAN }
		
		# Enum
		var regex4 = RegEx.new()
		regex4.compile("[a-zA-Z0-9_]+(\\.[a-zA-Z0-9_]+)")
		var result4 = regex4.search(str)
		
		if result4:
			color_map[result4.get_start()] = { "color": Color.ORANGE }
			color_map[result4.get_start(1)] = { "color": Color.ORANGE_RED }
			color_map[result4.get_end()] = { "color": Color.WHITE }
		
		# Color
		var regex2 = RegEx.new()
		regex2.compile("#[a-zA-Z0-9]+")
		var result2 = regex2.search(str)
		
		if result2:
			color_map[result2.get_start()] = { "color": Color(result2.get_string()) }
		
		

		return color_map