@page "/operations"

@using Hcs.WebApp.BackgroundServices
@using Hcs.WebApp.Services
@using Microsoft.AspNetCore.Authorization

@implements IDisposable

@attribute [Authorize]

@inject AuthenticationStateProvider AuthenticationStateProvider
@inject HeadquartersService HeadquartersService
@inject EventsAggregator EventsAggregator

<PageTitle>Операции</PageTitle>

<AuthorizedContent Roles="@($"{AppRole.ADMINISTRATOR_TYPE},{AppRole.OPERATOR_TYPE}")">
    <Content>
        <RadzenStack>
            <RadzenRow AlignItems="AlignItems.Center">
                <RadzenColumn Size="12" SizeMD="12">
                    <RadzenText Text="Операции" TextStyle="TextStyle.H5" class="rz-m-0" />
                </RadzenColumn>
            </RadzenRow>
            <RadzenRow>
                <RadzenColumn SizeMD="12">
                    <RadzenDataGrid @ref="@dataGrid" TItem="Operation" Data="@operations" IsLoading="@(state != PageState.Idle)" AllowFiltering="true" AllowPaging="true" ShowPagingSummary="true" PageSizeOptions=@(new int[] { 5, 10, 20, 30 }) AllowSorting="true" AllowColumnResize="true">
                        <Columns>
                            <RadzenDataGridColumn TItem="Operation" Property="@nameof(Operation.Id)" Title="ID" SortOrder="SortOrder.Descending" Resizable="false" Width="100px" MaxWidth="100px" />
                            <RadzenDataGridColumn TItem="Operation" Property="@nameof(Operation.CampaignId)" Title="ID кампании" Resizable="false" Width="100px" MaxWidth="100px" />
                            <RadzenDataGridColumn TItem="Operation" Property="@nameof(Operation.Type)" Title="Тип операции" />
                            <RadzenDataGridColumn TItem="Operation" Property="@nameof(Operation.CreatedAt)" Title="Дата создания" Resizable="false" Width="150px" MaxWidth="150px" />
                            <RadzenDataGridColumn TItem="Operation" Property="@nameof(Operation.StartedAt)" Title="Дата начала" Resizable="false" Width="150px" MaxWidth="150px" />
                            <RadzenDataGridColumn TItem="Operation" Property="@nameof(Operation.EndedAt)" Title="Дата окончания" Resizable="false" Width="150px" MaxWidth="150px" />
                            <RadzenDataGridColumn TItem="Operation" Property="@nameof(Operation.MessageGuid)" Title="ID сообщения" />
                            <RadzenDataGridColumn TItem="Operation" Property="@nameof(Operation.FailureReason)" Title="Причина ошибки" />
                        </Columns>
                    </RadzenDataGrid>
                </RadzenColumn>
            </RadzenRow>
        </RadzenStack>
    </Content>
</AuthorizedContent>

@code {
    PageState state;
    RadzenDataGrid<Operation> dataGrid;
    ICollection<Operation>? operations;

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

        if (firstRender)
        {
            ChangeState(PageState.Loading);

            var state = await AuthenticationStateProvider.GetAuthenticationStateAsync();
            if (state.User.IsOperatorOrHigher())
            {
                operations = await HeadquartersService.GetOperationsAsync();

                EventsAggregator.OnOperationCreated += OnOperationCreated;
                EventsAggregator.OnOperationStarted += OnOperationStarted;
                EventsAggregator.OnOperationExecuted += OnOperationExecuted;
                EventsAggregator.OnOperationEnded += OnOperationEnded;
            }

            ChangeState(PageState.Idle);
        }
    }

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

        this.state = state;

        StateHasChanged();
    }

    void OnOperationCreated(Operation operation)
    {
        InvokeAsync(() =>
        {
            operations?.Add(operation);

            dataGrid.Reload();
        });
    }

    void OnOperationStarted(int operationId, int campaignId, DateTime startedAt)
    {
        InvokeAsync(() =>
        {
            var targetOperation = operations?.FirstOrDefault(x => x.Id == operationId);
            if (targetOperation != null)
            {
                targetOperation.StartedAt = startedAt;

                dataGrid.Reload();
            }
        });
    }

    void OnOperationExecuted(int operationId, int campaignId, string messageGuid)
    {
        InvokeAsync(() =>
        {
            var targetOperation = operations?.FirstOrDefault(x => x.Id == operationId);
            if (targetOperation != null)
            {
                targetOperation.MessageGuid = messageGuid;

                dataGrid.Reload();
            }
        });
    }

    void OnOperationEnded(int operationId, int campaignId, DateTime endedAt, string failureReason)
    {
        InvokeAsync(() =>
        {
            var targetOperation = operations?.FirstOrDefault(x => x.Id == operationId);
            if (targetOperation != null)
            {
                targetOperation.EndedAt = endedAt;
                targetOperation.FailureReason = failureReason;

                dataGrid.Reload();
            }
        });
    }

    public void Dispose()
    {
        EventsAggregator.OnOperationCreated -= OnOperationCreated;
        EventsAggregator.OnOperationStarted -= OnOperationStarted;
        EventsAggregator.OnOperationExecuted -= OnOperationExecuted;
        EventsAggregator.OnOperationEnded -= OnOperationEnded;
    }
}
