@page "/registry/common"

@using System.IdentityModel.Claims
@using Hcs.WebApp.BackgroundServices
@using Hcs.WebApp.Components.Dialogs
@using Hcs.WebApp.Services
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Identity
@using Microsoft.EntityFrameworkCore

@implements IDisposable

@attribute [Authorize]

@inject AuthenticationStateProvider AuthenticationStateProvider
@inject HeadquartersService HeadquartersService
@inject RegistryService RegistryService
@inject DialogService DialogService
@inject CampaignManagementState CampaignManagementState

<PageTitle>Общие справочники подсистемы НСИ</PageTitle>

<AuthorizedContent Roles="@($"{AppRole.ADMINISTRATOR_TYPE},{AppRole.OPERATOR_TYPE}")">
    <Content>
        <RadzenStack>
            <RadzenRow AlignItems="AlignItems.Center">
                <RadzenColumn Size="12" SizeMD="6">
                    <RadzenText Text="Общие справочники подсистемы НСИ" TextStyle="TextStyle.H5" class="rz-m-0" />
                </RadzenColumn>
                <RadzenColumn Size="12" SizeMD="6">
                    <RadzenStack Orientation="Orientation.Horizontal" AlignItems="AlignItems.Center" JustifyContent="JustifyContent.End" Gap="0.5rem">
                        <RadzenButton Icon="sync" Text="@syncText" Disabled="@(state != CommonPageState.Idle)" Click="@SyncRegistriesAsync" ButtonStyle="ButtonStyle.Primary" />
                    </RadzenStack>
                </RadzenColumn>
            </RadzenRow>
            <RadzenRow>
                <RadzenColumn SizeMD="12">
                    <RadzenAlert Visible="@hasError" AlertStyle="AlertStyle.Danger" Variant="Variant.Flat" Shade="Shade.Lighter" AllowClose="false">
                        @errorMessage
                    </RadzenAlert>
                    <RadzenDataGrid TItem="Registry" Data="@registries" RowExpand="@RowExpandAsync" IsLoading="@(state != CommonPageState.Idle)" AllowFiltering="true" AllowPaging="true" ShowPagingSummary="true" PageSizeOptions=@(new int[] { 5, 10, 20, 30 }) AllowSorting="true" ExpandMode="DataGridExpandMode.Single">
                        <Template Context="registry">
                            <RadzenDataGrid Data="@registry.Elements" AllowFiltering="true" AllowSorting="true">
                                <Columns>
                                    <RadzenDataGridColumn Property="Code" Title="Код" SortOrder="SortOrder.Ascending" Resizable="false" Width="100px" MaxWidth="100px" />
                                    <RadzenDataGridColumn Property="GUID" Title="Идентификатор" />
                                    <RadzenDataGridColumn Filterable="false" Sortable="false" TextAlign="TextAlign.Center" Width="70px">
                                        <Template Context="registryElement">
                                            <RadzenButton Click="@(() => ShowElementAsync(registryElement))" @onclick:stopPropagation="true" ButtonStyle="ButtonStyle.Primary" Icon="visibility" Size="ButtonSize.Small" />
                                        </Template>
                                    </RadzenDataGridColumn>
                                </Columns>
                            </RadzenDataGrid>
                        </Template>
                        <Columns>
                            <RadzenDataGridColumn TItem="Registry" Property="Number" Title="Номер" Resizable="false" Width="100px" MaxWidth="100px" />
                            <RadzenDataGridColumn TItem="Registry" Property="Name" Title="Название" />
                        </Columns>
                    </RadzenDataGrid>
                </RadzenColumn>
            </RadzenRow>
        </RadzenStack>
    </Content>
</AuthorizedContent>

@code {
    enum CommonPageState
    {
        Init,
        Loading,
        Idle,
        OperationWaiting
    }

    CommonPageState state;
    IEnumerable<Registry> registries;
    string syncText = "...";
    bool hasError;
    string errorMessage;

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

        if (firstRender)
        {
            ChangeState(CommonPageState.Init);

            var finalState = CommonPageState.Idle;
            var state = await AuthenticationStateProvider.GetAuthenticationStateAsync();
            if (state.User.IsInRole(AppRole.ADMINISTRATOR_TYPE) || state.User.IsInRole(AppRole.OPERATOR_TYPE))
            {
                var operationInProgress = await HeadquartersService.HasActiveCampaignAsync(Campaign.CampaignType.ExportCommonRegistryElements_15_7_0_1);
                if (operationInProgress)
                {
                    finalState = CommonPageState.OperationWaiting;
                }

                CampaignManagementState.OnCampaignCreated += OnCampaignCreated;
                CampaignManagementState.OnCampaignEnded += OnCampaignEnded;

                registries = await RegistryService.GetAllRegistriesAsync(true);
            }

            ChangeState(finalState);
        }
    }

    async Task SyncRegistriesAsync()
    {
        if (state == CommonPageState.OperationWaiting) return;

        ChangeState(CommonPageState.OperationWaiting);

        if (await HeadquartersService.HasActiveCampaignAsync(Campaign.CampaignType.ExportCommonRegistryElements_15_7_0_1))
        {
            ChangeState(CommonPageState.Idle);
        }
        else
        {
            // TODO: Use user id
            var campaign = await HeadquartersService.InitiateCampaignAsync(Campaign.CampaignType.ExportCommonRegistryElements_15_7_0_1, "");
            CampaignManagementState.EnqueueCampaign(campaign);
        }
    }

    async Task RowExpandAsync(Registry registry)
    {
        if (registry.Elements == null)
        {
            registry.Elements = await RegistryService.GetRegistryElementsAsync(registry.Id);
        }
    }

    async Task ShowElementAsync(RegistryElement registryElement)
    {
        await DialogService.OpenAsync<ViewRegistryElement>(
            "Просмотр записи",
            new Dictionary<string, object>()
            {
                { nameof(ViewRegistryElement.RegistryElement), registryElement }
            },
            new DialogOptions()
            {
                Width = "420px",
                Height = "600px"
            });
    }

    void ChangeState(CommonPageState state)
    {
        if (this.state == state) return;

        this.state = state;

        SetSyncText();
        StateHasChanged();
    }

    void SetSyncText()
    {
        switch (state)
        {
            case CommonPageState.Init:
                syncText = "...";
                break;

            case CommonPageState.Loading:
            case CommonPageState.Idle:
                syncText = "Синхронизировать";
                break;

            case CommonPageState.OperationWaiting:
                syncText = "Идет синхронизация...";
                break;
        }
    }

    void OnCampaignCreated(Campaign campaign)
    {
        if (campaign.Type == Campaign.CampaignType.ExportCommonRegistryElements_15_7_0_1)
        {
            InvokeAsync(() => ChangeState(CommonPageState.OperationWaiting));
        }
    }

    void OnCampaignEnded(Campaign campaign)
    {
        if (campaign.Type == Campaign.CampaignType.ExportCommonRegistryElements_15_7_0_1)
        {
            Task.Run(RefreshRegistries);
        }
    }

    async Task RefreshRegistries()
    {
        await InvokeAsync(() => ChangeState(CommonPageState.Loading));

        var refreshedRegistries = await RegistryService.GetAllRegistriesAsync(true);

        await InvokeAsync(() =>
        {
            registries = refreshedRegistries;

            ChangeState(CommonPageState.Idle);
        });
    }

    public void Dispose()
    {
        CampaignManagementState.OnCampaignCreated -= OnCampaignCreated;
        CampaignManagementState.OnCampaignEnded -= OnCampaignEnded;
    }
}
