@page "/open-acs"
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using RobotNet.RobotShares.OpenACS
@using RobotNet.Shares
@using RobotNet.WebApp.Robots.Components.OpenACS
@attribute [Authorize]

@inject IHttpClientFactory HttpClientFactory

<PageTitle>Open ACS</PageTitle>

<div class="d-flex flex-row w-100 h-100 p-1 position-relative">
    <div style="width: 35%; max-width: 560px; overflow-y: auto; overflow-x: hidden">
        <PublishSetting @ref="PublishSettingRef" SettingDto="@PublishSettingDto.PublishSetting" />
        <TrafficSetting @ref="TrafficSettingRef" SettingDto="@PublishSettingDto.TrafficSetting" />
        <TrafficRequest />
        <DashboardConfig />
    </div>
    <div style="width: 65%" class="ms-2 flex-grow-1 flex-column">
        <div style="height: 70%">
            <ACSLog />
        </div>
        <div style="height: 28%" class="flex-grow-1 mt-2">
            <TrafficACSLockedView />
        </div>
    </div>

    <MudOverlay @bind-Visible="OverlayIsVisible" DarkBackground="true" Absolute="true">
        <MudText Typo="Typo.h1" Color="@Color.Error" Style="font-weight: bold;">Loadding...</MudText>
    </MudOverlay>
</div>

@code {
    private OpenACSSettingsDto PublishSettingDto = new();
    private bool OverlayIsVisible = false;

    private PublishSetting PublishSettingRef = default!;
    private TrafficSetting TrafficSettingRef = default!;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);
        if (!firstRender) return;

        await LoadSettings();
    }

    private async Task LoadSettings()
    {
        try
        {
            OverlayIsVisible = true;
            StateHasChanged();

            using var client = HttpClientFactory.CreateClient("RobotManagerAPI");
            var settings = await client.GetFromJsonAsync<MessageResult<OpenACSSettingsDto>>("api/OpenACSSettings");
            if (settings is null || settings.Data is null || !settings.IsSuccess) PublishSettingDto = new();
            else PublishSettingDto = settings.Data;

            PublishSettingRef.UpdateSettings(PublishSettingDto.PublishSetting);
            TrafficSettingRef.UpdateSettings(PublishSettingDto.TrafficSetting);

            OverlayIsVisible = false;
            StateHasChanged();
        }
        catch (AccessTokenNotAvailableException ex)
        {
            ex.Redirect();
        }
    }
}
