extends Node

#export(Dictionary) var progress_dict := {} setget set_progress, get_progress
#export(int) var wallet := 0 setget set_wallet
#export(Dictionary) var input_map
#export(bool) var show_tutorial
export(Resource) var gsr
var sound_library = {}

func _ready():
    load_sounds()

func load_sounds() -> void:
    var paths = ["res://assets/sounds","res://assets/music"]
    for path in paths:
        var dir = Directory.new()
        dir.open(path)
        dir.list_dir_begin()
        while true:
            var file_name = dir.get_next()
            if file_name == "":
                break
            var sound_file
            if file_name.ends_with(".import"):
                sound_file = load(path + "/" + file_name.split(".import")[0])
                sound_library[sound_file.resource_path] = sound_file
        dir.list_dir_end()

func set_progress(value) -> void:
    gsr.progress_dict = value
    SaveManager.save_default()

func get_progress() -> Dictionary:
    return gsr.progress_dict

func save() -> void:
    SaveManager.save_default()

func set_savepoint(levelName: String, position: Vector2) -> void:
    #TODO You can free a frog, go to the checkpoint and it will be 
    # saved as freed forever
    if(!gsr.progress_dict.has(levelName)):
        gsr.progress_dict[levelName] = {}
    gsr.progress_dict[levelName]["savepoint"] = position
    SaveManager.save_default()
    
func remove_savepoint(levelName: String) -> void:
    if(!gsr.progress_dict.has(levelName)):
        return
    gsr.progress_dict[levelName].erase(levelName)
    SaveManager.save_default()
    

func get_property_value(levelName: String, propertyName: String) -> int:
    if gsr.progress_dict.has(levelName) && gsr.progress_dict[levelName].has(propertyName):
        return gsr.progress_dict[levelName][propertyName]
    else:
        return 0

func get_savepoint(levelName: String) -> Vector2:
    if gsr.progress_dict.has(levelName) && gsr.progress_dict[levelName].has("savepoint"):
        return gsr.progress_dict[levelName]["savepoint"]
    else:
        return Vector2()

# TODO This is permanent immediatly
func set_wallet(value) -> void:
    gsr.wallet = value
    SaveManager.save_default()

func reinstate() -> void:
    if gsr.input_map.size() <= 1:
        InputMap.load_from_globals()
        return
    for action in gsr.input_map:
        InputMap.action_erase_events(action)
        # if(gsr.input_map[action].size() > 0 && gsr.input_map[action].size() < 2):
        # 	InputMap.load_from_globals()
        for input_event in gsr.input_map[action]:
            InputMap.action_add_event(action, input_event)
