extends Node

export var splash_screen_path: String
export var main_menu_path: String
export var level_select_menu_path: String
export var world_path: String


func _ready() -> void:
    var splash_screen: Node = play_splash_screen()
    yield(splash_screen, 'complete')
    splash_screen = null

    var main_menu: Node = play_main_menu()
    yield(main_menu, 'complete')
    free_connected_node(main_menu, 'main_menu_option')
    main_menu = null
    return


func play_splash_screen() -> Node:
    var splash_screen: Node = load(splash_screen_path).instance()
    if splash_screen.connect('complete', self, 'free_connected_node',
            [splash_screen, 'free_connected_node']) != OK:
        print('ERROR: Splash Screen "complete" signal already connected.')

    add_child(splash_screen)
    return splash_screen


func play_main_menu() -> Node:
    var main_menu: Node = load(main_menu_path).instance()
    if main_menu.connect('complete', self, 'main_menu_option') != OK:
        print('ERROR: Main Menu "complete" signal already connected.')

    add_child(main_menu)
    return main_menu


func main_menu_option(option: String) -> void:
    if option == 'new game':
        var level_select_menu: Node = play_level_select_menu()
        yield(level_select_menu, 'complete')
        free_connected_node(level_select_menu, 'level_select_menu_option')
        level_select_menu = null
    return


func play_level_select_menu() -> Node:
    var level_select_menu: Node = load(level_select_menu_path).instance()
    if level_select_menu.connect('complete', self, 'level_select_menu_option') != OK:
        print('ERROR: Level Select Menu "complete" signal already connected.')

    add_child(level_select_menu)
    return level_select_menu


func level_select_menu_option(option: String) -> void:
    var level: String = 'res://Levels/'
    if option == 'H':
        level += 'Hub World.tscn'
    else:
        level += 'Level ' + option + '.tscn'

    new_game(level)
    return


func free_connected_node(node: Node, connected_function: String) -> void:
    node.disconnect('complete', self, connected_function)
    remove_child(node)
    node.queue_free()
    return


func new_game(level: String) -> void:
    if get_tree().change_scene(level) != OK:
        print('ERROR: Main failed to change scene to Level.')
    queue_free()
    return
