using Godot;
using Microsoft.Data.Sqlite;
using System;
using System.Collections.Generic;
using System.IO;

namespace SessionZeroApp;

public partial class AppManager : Node
{

    

    public static AppManager Instance { get; private set; }
    
    public ApplicationSettingsResource AppSettings { get; private set; }
    public CanvasLayer MainCanvas { get; private set; }
    public Node MainNode { get; private set; }
    public MainUILogic MainUI { get; private set; }

    public Dictionary<string, ContentPageBase> Pages { get; private set; } = [];

    private PackedScene _mainUiScene;
    

    public override void _Ready()
    {
        Instance = this;

        LocalDatabaseHelper.SetupLocalDatabase();

        try
        {
            AppSettings = ResourceLoader.Load<ApplicationSettingsResource>("res://AppSettings.tres");
        }
        catch (InvalidCastException e)
        {
            GD.PrintErr($"Failed to get the AppSettings resource: {e}");
            return;
        }

        _mainUiScene = AppSettings.MainUiScene;

        foreach (var scene in AppSettings.Pages)
        {
            try
            {
                var newPage = scene.Instantiate<ContentPageBase>();
                Pages[newPage.PageName] = newPage;
            }
            catch (InvalidCastException e)
            {
                GD.PrintErr($"Couldn't add page '{scene.ResourceName}': {e}");
                continue;
            }
        }


        MainCanvas = new();
        GetTree().Root.CallDeferred("add_child", MainCanvas);

        MainNode = GetTree().Root.GetNode<Node>("Main");

        try
        {
            MainUI = _mainUiScene.Instantiate<MainUILogic>();
        }
        catch (InvalidCastException e)
        {
            GD.PrintErr($"Failed to setup the MainUI scene: {e}");
            return;
        }

        MainCanvas.AddChild(MainUI);

        LoadPage("Home");
    }

    

    public void LoadPage(string pageName)
    {
        if (!Pages.TryGetValue(pageName, out ContentPageBase value))
        {
            GD.PrintRich($"[color=yellow]Couldn't find page '{pageName}'[/color]");
            return;
        }

        MainUI.LoadPageContent(value);
    }
}
