@using RobotNet.RobotShares.OpenACS

@inject IHttpClientFactory HttpFactory
@inject ISnackbar Snackbar

<div class="view-paper">
    <div class="d-flex" style="height: fit-content;">
        <MudSelect Class="mt-1 ms-2 d-flex justify-content-center" T="RobotACSLockedDto" Adornment="Adornment.End" @bind-Value="RobotSeleced"
                   IconSize="Size.Medium" Variant="Variant.Text" Margin="Margin.Dense" AdornmentColor="Color.Secondary" Label="Robot">
            @foreach(var robot in RobotACSLockedDto)
            {
                <MudSelectItem Value="robot">@robot.RobotId</MudSelectItem>
            }
        </MudSelect>
        <MudSpacer />
        <div class="m-1 d-flex flex-row">
            <MudTooltip Text="Refresh">
                <MudFab Class="mx-4 mt-2" StartIcon="@Icons.Material.Filled.Refresh" Color="Color.Primary" Size="Size.Small" OnClick="@(async () => await LoadRobots())" />
            </MudTooltip>
        </div>
    </div>
    <div class="content">
        @if(RobotSeleced is not null)
        {
            foreach(var zone in RobotSeleced.ZoneIds)
            {
                <div class="zone">
                    <span>@zone</span>
                </div>
            }
        }
    </div>
</div>

@code {
    private RobotACSLockedDto[] RobotACSLockedDto = [];
    private RobotACSLockedDto? RobotSeleced = null;

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

    private async Task LoadRobots()
    {
        RobotACSLockedDto = [];
        using var Http = HttpFactory.CreateClient("RobotManagerAPI");
        var robots = await Http.GetFromJsonAsync<RobotACSLockedDto[]>("api/TrafficACSRequest");
        if (robots is null) Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
        else if (robots.Length > 0)
        {
            RobotACSLockedDto = [..robots.OrderByDescending(robot => robot.RobotId)];
            RobotSeleced = RobotACSLockedDto.First();
        }
        StateHasChanged();
    }
}
