@page "/"

@using DiscordBotCore.Others.Exceptions
@using DiscordBotWebUI.Components.Pages.Setup
@using DiscordBotWebUI.DiscordBot

@inject DialogService DialogService

<RadzenButton Text="Start" Click="Initialize"/>
<RadzenTextArea Placeholder="Logs..." Value="@_TextValue" Style="width: 100%; height: 80%"/>


@code {
    private string? _TextValue;

    private DiscordBotStartup _DiscordBotStartup = null!;

    
    protected override async Task OnAfterRenderAsync(bool firstRender) 
    {
        // Only run after the first render
        if(!firstRender)
        {
            return;
        }
        
        
        _DiscordBotStartup = new DiscordBotStartup {RequirementsSolver = FixModules};
        await _DiscordBotStartup.CreateApplication();
    }

    private async Task FixModules(ModuleRequirement requirements)
    {
        if(!requirements.RequireAny)
        {
            return;
        }

        await DialogService.OpenAsync<InstallRequiredModules>("Some required modules are not installed. Please install before using the bot ...", new Dictionary<string, object>()
        {
            {"Requirements", requirements}
        }, new DialogOptions() { Width = "75%", Height = "75%" });
   }

    private async void Initialize()
    {
        _DiscordBotStartup.Log = async (str, type) => {
            _TextValue += $"[{type}] {str} \n";
            await InvokeAsync(StateHasChanged);
            
            Console.WriteLine(str);
        };

        if (_DiscordBotStartup.LoadComponents())
        {
            await _DiscordBotStartup.PrepareBot();
            await _DiscordBotStartup.RefreshPlugins(false);

            return;
        }

        while (await DialogService.OpenAsync<Settings>("Please complete this setup before starting the bot") == false)
        {
            Console.WriteLine("Failed to complete the setup. Invalid data acquired ...");
        }
        
        

        await _DiscordBotStartup.PrepareBot();
        await _DiscordBotStartup.RefreshPlugins(false);
    }
}