extends CanvasLayer

@onready var rect = $ColorRect
@onready var log_display = $RichTextLabel

func _ready():
	rect.modulate.a = 0
	log_display.text = ""
	log_display.visible = false

	rect.mouse_filter = Control.MOUSE_FILTER_IGNORE

func change_scene(target_path: PackedScene, is_error: bool = false):
	var player : Player= get_tree().get_first_node_in_group("player")
	var player_mask : MaskData = null
	if player:
		player_mask = player.current_mask_data 
	
	rect.mouse_filter = Control.MOUSE_FILTER_STOP
	
	if is_error:
		rect.color = Color.CRIMSON
	else:
		rect.color = Color.from_string("#364388", Color.BLUE)
	
	var tween_in = create_tween()
	await tween_in.tween_property(rect, "modulate:a", 1.0, 0.3).finished
	
	log_display.visible = true
	var log_file = "res://hex.txt" if is_error else "res://log.txt"
	display_log_file(log_file)
	
	await get_tree().create_timer(0.1).timeout
	var error = get_tree().change_scene_to_packed(target_path)
	if error != OK:
		push_error("Failed to load scene")
	await get_tree().scene_changed

	log_display.visible = false
	log_display.text = ""
	
	var tween_out = create_tween()
	tween_out.tween_property(rect, "modulate:a", 0.0, 0.5)
	rect.mouse_filter = Control.MOUSE_FILTER_IGNORE

	player = get_tree().get_first_node_in_group("player")
	if player and player_mask:
		player.equip_mask(player_mask)

func display_log_file(file_path: String):
	if not FileAccess.file_exists(file_path):
		log_display.add_text(file_path + " not found\n")
		return

	var file = FileAccess.open(file_path, FileAccess.READ)
	if not file:
		log_display.add_text("cant open file\n")
		return

	while not file.eof_reached():
		for i in range(randi() % 4):
			var line = file.get_line()
			if line.strip_edges() == "": continue 
			
			log_display.add_text(line + "\n")
			log_display.scroll_to_line(log_display.get_line_count())
		
		var delay = 0#randf_range(0.0001, 0.00015)
		#if randf() > 0.95:
			#delay += 0.2 # Random "loading" hitch for realism
			
		await get_tree().create_timer(delay).timeout
