@using RobotNet.RobotShares.OpenACS
@inject ISnackbar Snackbar
@inject IHttpClientFactory HttpClientFactory

<MudCard Class="w-100 me-2 position-relative mt-2" Elevation="0" Outlined Style="height: 370px">
    <MudCardHeader>
        <MudText Typo="Typo.h5">Traffic Request</MudText>
    </MudCardHeader>
    <MudCardContent>
        <div class="d-flex flex-column">
            <MudAutocomplete T="string" Variant="Variant.Outlined" Label="Robot Id" ShrinkLabel Modal SearchFunc="UrlSearch"
            CoerceText="false" CoerceValue="true" MaxItems="Robots.Length" ShowProgressIndicator="true" @bind-Value="RobotId">
            </MudAutocomplete>
            <MudTextField Label="Zone Id" Variant="Variant.Outlined" @bind-Value="ZoneId" ShrinkLabel />
            <MudSelect T="TrafficRequestType" Label="Type" @bind-Value="@Type" Variant="Variant.Outlined">
                @foreach (TrafficRequestType item in Enum.GetValues(typeof(TrafficRequestType)))
                {
                    <MudSelectItem Value="@item" />
                }
            </MudSelect>
            <div class="d-flex flex-row-reverse mt-4">
                <div>
                    <MudButton Class="d-flex flex-grow-1 mt-2 mb-1 ms-2" Variant="Variant.Filled" Color="Color.Info" OnClick="Request">Request</MudButton>
                </div>
            </div>
        </div>
    </MudCardContent>

    <MudOverlay Visible="OverlayIsVisible" DarkBackground="true" Absolute="true">
        <MudProgressCircular Color="Color.Secondary" Indeterminate="true" />
    </MudOverlay>
</MudCard>

@code {
    private bool OverlayIsVisible;

    private RobotDto[] Robots = [];
    private string RobotId = string.Empty;
    private string ZoneId = string.Empty;
    private TrafficRequestType Type = TrafficRequestType.OUT;

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

    private async Task LoadRobots()
    {
        OverlayIsVisible = true;
        StateHasChanged();

        using var Http = HttpClientFactory.CreateClient("RobotManagerAPI");
        var robots = await Http.GetFromJsonAsync<MessageResult<IEnumerable<RobotDto>>>("api/Robots");
        if (robots is null) Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
        else if (!robots.IsSuccess) Snackbar.Add($"Có lỗi xảy ra: {robots.Message}", Severity.Error);
        else if (robots.Data is not null && robots.Data.Any())
        {
            Robots = [..robots.Data];
        }
        OverlayIsVisible = false;
        StateHasChanged();
    }


    private async Task<IEnumerable<string>> UrlSearch(string value, CancellationToken token)
    {
        await Task.Delay(5, token);

        if (string.IsNullOrEmpty(value))
        {
            return Robots.Select(n => n.Name);
        }

        return Robots.Where(x => x.Name.Contains(value, StringComparison.InvariantCultureIgnoreCase)).Select(n => n.Name);
    }

    private async Task Request()
    {
        if(string.IsNullOrEmpty(RobotId)) 
        {
            Snackbar.Add($"Trường thông tin Robot Id không được để trống", Severity.Warning);
            return;
        }
        if (string.IsNullOrEmpty(ZoneId))
        {
            Snackbar.Add($"Trường thông tin Zone Id không được để trống", Severity.Warning);
            return;
        }

        OverlayIsVisible = true;
        StateHasChanged();
        using var Http = HttpClientFactory.CreateClient("RobotManagerAPI");
        var request = await (await Http.PostAsJsonAsync("api/TrafficACSRequest", new TrafficACSRequestModel() { RobotId = RobotId, ZoneId = ZoneId, Type = Type})).Content.ReadFromJsonAsync<MessageResult<bool>>();
        if (request is null) Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Warning);
        else if (!request.IsSuccess) Snackbar.Add($"Có lỗi xảy ra: {request.Message}", Severity.Warning);
        else if (!request.Data) Snackbar.Add("ACS trả về không thành công thành công", Severity.Warning);
        else if (request.Data) Snackbar.Add($"{(string.IsNullOrEmpty(request.Message) ? "Yêu cầu thành công" : request.Message)}", Severity.Success);

        OverlayIsVisible = false;
        StateHasChanged();
    }
}
