@page "/campaigns"

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

@implements IDisposable

@attribute [Authorize]

@inject AuthenticationStateProvider AuthenticationStateProvider
@inject HeadquartersService HeadquartersService
@inject CampaignManagementState CampaignManagementState

<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 TItem="Campaign" Data="@campaigns" RowExpand="@RowExpandAsync" IsLoading="@(state != CampaignsPageState.Idle)" AllowFiltering="true" AllowPaging="true" ShowPagingSummary="true" PageSizeOptions=@(new int[] { 5, 10, 20, 30 }) AllowSorting="true" ExpandMode="DataGridExpandMode.Single">
                        <Template Context="campaign">
                            <RadzenDataGrid Data="@campaign.Operations" AllowFiltering="true" AllowPaging="true" ShowPagingSummary="true" PageSizeOptions=@(new int[] { 5, 10, 20, 30 }) AllowSorting="true">
                                <Columns>
                                    <RadzenDataGridColumn Property="Id" Title="ID" SortOrder="SortOrder.Descending" Resizable="false" Width="100px" MaxWidth="100px" />
                                    <RadzenDataGridColumn Property="Type" Title="Тип операции" Resizable="true" />
                                    <RadzenDataGridColumn Property="CreatedAt" Title="Дата создания" Resizable="false" Width="150px" MaxWidth="150px" />
                                    <RadzenDataGridColumn Property="StartedAt" Title="Дата начала" Resizable="false" Width="150px" MaxWidth="150px" />
                                    <RadzenDataGridColumn Property="StartedAt" Title="Дата окончания" Resizable="false" Width="150px" MaxWidth="150px" />
                                    <RadzenDataGridColumn Property="MessageGuid" Title="ID сообщения" Resizable="true" />
                                    <RadzenDataGridColumn Property="FailureReason" Title="Причина ошибки" Resizable="true" />
                                </Columns>
                            </RadzenDataGrid>
                        </Template>
                        <Columns>
                            <RadzenDataGridColumn TItem="Campaign" Property="Id" Title="ID" SortOrder="SortOrder.Descending" Resizable="false" Width="100px" MaxWidth="100px" />
                            <RadzenDataGridColumn TItem="Campaign" Property="Type" Title="Тип кампании" Resizable="true">
                                <Template Context="campaign">
                                    @CampaignTypeToString(campaign.Type)
                                </Template>
                            </RadzenDataGridColumn>
                            <RadzenDataGridColumn TItem="Campaign" Property="CreatedAt" Title="Дата создания" Resizable="false" Width="150px" MaxWidth="150px" />
                            <RadzenDataGridColumn TItem="Campaign" Property="StartedAt" Title="Дата начала" Resizable="false" Width="150px" MaxWidth="150px" />
                            <RadzenDataGridColumn TItem="Campaign" Property="StartedAt" Title="Дата окончания" Resizable="false" Width="150px" MaxWidth="150px" />
                            <RadzenDataGridColumn TItem="Campaign" Property="FailureReason" Title="Причина ошибки" Resizable="true" />
                        </Columns>
                    </RadzenDataGrid>
                </RadzenColumn>
            </RadzenRow>
        </RadzenStack>
    </Content>
</AuthorizedContent>

@code {
    enum CampaignsPageState
    {
        Init,
        Loading,
        Idle
    }

    CampaignsPageState state;
    IEnumerable<Campaign> campaigns;

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

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

            var state = await AuthenticationStateProvider.GetAuthenticationStateAsync();
            if (state.User.IsInRole(AppRole.ADMINISTRATOR_TYPE) || state.User.IsInRole(AppRole.OPERATOR_TYPE))
            {
                CampaignManagementState.OnCampaignCreated += OnCampaignCreated;
                CampaignManagementState.OnCampaignEnded += OnCampaignEnded;

                campaigns = await HeadquartersService.GetCampaignsAsync();
            }

            ChangeState(CampaignsPageState.Idle);
        }
    }

    async Task RowExpandAsync(Campaign campaign)
    {
        // TODO
    }

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

        this.state = state;

        StateHasChanged();
    }

    void OnCampaignCreated(Campaign campaign)
    {
        Task.Run(RefreshCampaigns);
    }

    void OnCampaignEnded(Campaign campaign)
    {
        Task.Run(RefreshCampaigns);
    }

    async Task RefreshCampaigns()
    {
        await InvokeAsync(() => ChangeState(CampaignsPageState.Loading));

        var refreshedCampaigns = await HeadquartersService.GetCampaignsAsync();

        await InvokeAsync(() =>
        {
            campaigns = refreshedCampaigns;

            ChangeState(CampaignsPageState.Idle);
        });
    }

    string CampaignTypeToString(Campaign.CampaignType campaignType)
    {
        return campaignType switch
        {
            Campaign.CampaignType.ExportPrivateRegistryElements_15_7_0_1 => "Экспорт частных справочников",
            Campaign.CampaignType.ExportCommonRegistryElements_15_7_0_1 => "Экспорт общих справочников",

            _ => "???"
        };
    }

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