extends Node

signal on_collectible_unlocked(collectible_id: StringName)
signal on_photo_saved(filePath: String)

var collectibles_library: CollectibleLibrary = preload("res://core/photo_mode/data/collectible_library.tres")

var unlocked_collectibles_ids: Array[StringName] = []
var saved_photos: Array[String] = []

func _ready() -> void:
	load_save_data()

func unlock_collectible(collectible_id: StringName) -> void:
	if not collectible_id in unlocked_collectibles_ids:
		var new_collectible = get_collectible_by_id(collectible_id)
		if new_collectible:
			unlocked_collectibles_ids.append(collectible_id)
			sync_save_data()
			on_collectible_unlocked.emit(collectible_id)

func get_collectible_by_id(id: StringName) -> CollectibleResource:
	for collectible in collectibles_library.collectibles:
		if collectible.id == id:
			return collectible
	return null

func get_all_collectibles() -> Array[CollectibleResource]:
	return collectibles_library.collectibles

func get_unlocked_collectible_ids() -> Array[StringName]:
	return unlocked_collectibles_ids

func save_photo_to_disk_async() -> void:
	await RenderingServer.frame_post_draw
	var image = get_viewport().get_texture().get_image()
	
	if not DirAccess.dir_exists_absolute("user://photos"):
		DirAccess.make_dir_absolute("user://photos")
	
	var timestamp = str(Time.get_unix_time_from_system())
	var file_path = "user://photos/photo_" + timestamp + ".png"
	image.save_png(file_path)
	
	saved_photos.append(file_path)
	sync_save_data()
	on_photo_saved.emit(file_path)

func sync_save_data() -> void:
	GameState.save_data.unlocked_collectibles_ids = unlocked_collectibles_ids.duplicate()
	GameState.save_data.saved_photos = saved_photos.duplicate()

func load_save_data() -> void:
	unlocked_collectibles_ids = GameState.save_data.unlocked_collectibles_ids.duplicate()
	saved_photos = GameState.save_data.saved_photos.duplicate()

	if unlocked_collectibles_ids.is_empty() and saved_photos.is_empty():
		unlocked_collectibles_ids.append(&"cane")

	sync_save_data()
