@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using RobotNet.RobotShares.OpenACS

@inject IHttpClientFactory HttpClientFactory
@inject ISnackbar Snackbar

<MudCard Class="w-100 me-2 position-relative" Elevation="0" Outlined Style="height: 350px">
    <MudCardHeader>
        <MudText Typo="Typo.h5">Publish Setting</MudText>
    </MudCardHeader>
    <MudCardContent>
        <div class="d-flex flex-column">
            <MudSwitch @bind-Value="NewSettingDto.IsPublishEnabled" Color="Color.Primary" Label="Enable" @bind-Value:after="EnableChanged" />
            <MudAutocomplete T="string" Variant="Variant.Outlined" Label="Url" ShrinkLabel Disabled="@NewSettingDto.IsPublishEnabled" Modal SearchFunc="UrlSearch"
                             CoerceText="false" CoerceValue="true" MaxItems="NewSettingDto.PublishUrlsUsed.Length" ShowProgressIndicator="true" @bind-Value="NewSettingDto.PublishUrl">
            </MudAutocomplete>
            <MudNumericField T="int" Label="Interval(ms)" @bind-Value="NewSettingDto.PublishInterval" Disabled="@NewSettingDto.IsPublishEnabled" Variant="Variant.Outlined" Min="500" />
            <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" Disabled="@NewSettingDto.IsPublishEnabled" OnClick="Update">Update</MudButton>
                </div>
            </div>
        </div>
    </MudCardContent>

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

@code {
    [Parameter, EditorRequired]
    public OpenACSPublishSettingDto SettingDto { get; set; } = new(false, "", [], 2000);

    private OpenACSPublishSettingDto NewSettingDto { get; set; } = new(false, "", [], 2000);
    private bool OverlayIsVisible;


    public void UpdateSettings(OpenACSPublishSettingDto settings)
    {
        SettingDto = settings;
        NewSettingDto = new()
        {
            IsPublishEnabled = SettingDto.IsPublishEnabled,
            PublishInterval = SettingDto.PublishInterval,
            PublishUrl = SettingDto.PublishUrl,
            PublishUrlsUsed = SettingDto.PublishUrlsUsed,
        };
        StateHasChanged();
    }

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

        if (string.IsNullOrEmpty(value))
        {
            return SettingDto.PublishUrlsUsed;
        }

        return SettingDto.PublishUrlsUsed.Where(x => x.Contains(value, StringComparison.InvariantCultureIgnoreCase));
    }

    private async Task Update()
    {
        try
        {
            if (NewSettingDto.PublishUrl == SettingDto.PublishUrl && NewSettingDto.PublishInterval == SettingDto.PublishInterval)
            {
                Snackbar.Add("Không có thay đổi nào để cập nhật", Severity.Warning);
                return;
            }

            OverlayIsVisible = true;
            StateHasChanged();

            using var Http = HttpClientFactory.CreateClient("RobotManagerAPI");

            var result = await (await Http.PostAsJsonAsync($"api/OpenACSSettings/publish", new OpenACSPublishSettingModel(NewSettingDto.PublishUrl, NewSettingDto.PublishInterval))).Content.ReadFromJsonAsync<MessageResult<OpenACSPublishSettingDto>>();
            if (result is null) { Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Warning); return; }
            else if (!result.IsSuccess) { Snackbar.Add(result.Message ?? "Cập nhật không thành công", Severity.Warning); return; }
            else if (result.Data == null)
            {
                Snackbar.Add("Lỗi dữ liệu trả về", Severity.Warning);
                return;
            }
            SettingDto = result.Data;
            NewSettingDto = new()
            {
                IsPublishEnabled = SettingDto.IsPublishEnabled,
                PublishInterval = SettingDto.PublishInterval,
                PublishUrl = SettingDto.PublishUrl,
                PublishUrlsUsed = SettingDto.PublishUrlsUsed,
            };

            OverlayIsVisible = false;
            Snackbar.Add("Cập nhật thành công", Severity.Success);
            StateHasChanged();
        }
        catch (AccessTokenNotAvailableException ex)
        {
            ex.Redirect();
        }
    }

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

            using var Http = HttpClientFactory.CreateClient("RobotManagerAPI");
            var result = await Http.GetFromJsonAsync<MessageResult>($"api/OpenACSSettings/publish?enable={NewSettingDto.IsPublishEnabled}");
            if (result is null) { Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error); return; }
            else if (!result.IsSuccess) { Snackbar.Add(result.Message ?? "Cập nhật không thành công", Severity.Warning); return; }

            SettingDto.IsPublishEnabled = NewSettingDto.IsPublishEnabled;

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