@page "/test/export"

@using Hcs.Broker
@using Hcs.Broker.Logger
@using Hcs.Broker.MessageCapturer
@using Hcs.Service.Async.Nsi
@using Hcs.WebApp.Config
@using Hcs.WebApp.Services
@using Hcs.WebApp.Utils
@using Microsoft.AspNetCore.Authorization

@attribute [Authorize]

@implements IDisposable

@inject NavigationManager NavigationManager
@inject IConfiguration Configuration
@inject IClientProvider ClientProvider

<PageTitle>Тестирование экспорта</PageTitle>

<AuthorizedContent Roles="@AppRole.ADMINISTRATOR_TYPE">
    <Content>
        <RadzenSplitter Orientation="Orientation.Vertical" Style="height: 100%; border: 1px solid rgba(0,0,0,.08);">
            <RadzenSplitterPane Size="200px">
                <div style="height: 100%;overflow: auto;">
                    <RadzenCardGroup Responsive="true">
                        <RadzenCard Variant="Variant.Filled">
                            <RadzenStack JustifyContent="JustifyContent.SpaceBetween" Gap="1rem">
                                <RadzenStack Orientation="Orientation.Vertical" AlignItems="AlignItems.Start" JustifyContent="JustifyContent.Normal">
                                    <RadzenText TextStyle="TextStyle.H6">Сервис nsi</RadzenText>
                                    <RadzenButton Click="@OnNsiExportItem1ClickAsync" Disabled=@inputDisabled Text="Экспорт НСИ 1" ButtonStyle="ButtonStyle.Primary" />
                                </RadzenStack>
                            </RadzenStack>
                        </RadzenCard>
                    </RadzenCardGroup>
                </div>
            </RadzenSplitterPane>
            <RadzenSplitterPane>
                <RadzenTabs RenderMode="TabRenderMode.Client" Style="height: 100%;">
                    <Tabs>
                        <RadzenTabsItem Text="Запрос">
                            <RadzenTextArea @ref=@messageTextArea Value=@messageBody Disabled="true" ReadOnly="true" Style="resize: none; white-space: pre; overflow-wrap: normal; overflow-x: auto;" class="rz-w-stretch" />
                        </RadzenTabsItem>
                        <RadzenTabsItem Text="Результат">
                            <RadzenTextArea @ref=@responseTextArea Value=@responseBody Disabled="true" ReadOnly="true" Style="resize: none; white-space: pre; overflow-wrap: normal; overflow-x: auto;" class="rz-w-stretch" />
                        </RadzenTabsItem>
                    </Tabs>
                </RadzenTabs>
            </RadzenSplitterPane>
            <RadzenSplitterPane Size="auto" Resizable="false">
                <EventConsole @ref=@console />
            </RadzenSplitterPane>
        </RadzenSplitter>
    </Content>
</AuthorizedContent>

@code {
    EventConsole console = default!;
    bool inputDisabled = false;
    RadzenTextArea messageTextArea;
    RadzenTextArea responseTextArea;
    string messageBody;
    string responseBody;

    IClient client;
    ActionLogger logger = new ActionLogger();
    FileMessageCapturer messageCapturer;
    bool catchMessageBody;

    public void Dispose()
    {
        if (messageCapturer != null)
        {
            messageCapturer.OnFileWritten -= OnFileWritten;
        }
    }

    void OnLog(string log)
    {
        console.Log(log);
    }

    void OnFileWritten(string fileName)
    {
        if (catchMessageBody)
        {
            catchMessageBody = false;

            messageBody = XmlBeautifier.Beautify(File.ReadAllText(fileName));
            messageTextArea.Rows = messageBody.Count(c => c.Equals('\n')) + 2;
        }
    }

    async Task OnNsiExportItem1ClickAsync()
    {
        try
        {
            TryInitializeClient();
            StartExport();

            await client.Nsi.ExportDataProviderNsiItemAsync(exportDataProviderNsiItemRequestRegistryNumber.Item1);

            EndExport();
        }
        catch
        {
            NavigationManager.NavigateTo("/error");
        }
    }

    void TryInitializeClient()
    {
        if (client == null)
        {
            logger.OnWriteLine += OnLog;

            messageCapturer = new FileMessageCapturer("test/export", logger);
            messageCapturer.OnFileWritten += OnFileWritten;

            var config = Configuration.GetSection("BrokerConfig").Get<BrokerConfig>();
            client = ClientProvider.CreateClient(config, logger, messageCapturer);
        }
    }

    void StartExport()
    {
        inputDisabled = true;
        messageBody = string.Empty;
        responseBody = string.Empty;
        catchMessageBody = true;

        console.Clear();
    }

    void EndExport()
    {
        inputDisabled = false;
        responseBody = XmlBeautifier.Beautify(File.ReadAllText(messageCapturer.LastFileName));
        responseTextArea.Rows = responseBody.Count(c => c.Equals('\n')) + 2;
    }
}
