using Insight.Infrastructure;
using Insight.Infrastructure.Entities;
using Insight.Web.Constants;
using Insight.Web.Messages;
using Insight.Web.Network;
using Microsoft.AspNetCore.Components;
using MongoDB.Bson;
using MongoDB.Driver;
using MudBlazor;
using Vaitr.MemoryBus;
using Vaitr.Network;

namespace Insight.Web.Pages.Management.Hosts.Actions.Console;

[Route(Navigation.Management.Hosts.Actions.Console.Index)]
public partial class Index
{
    [Parameter] public string? HostId { get; set; }

    [Inject] private TcpSessionPool<WebSession, MemPackSerializer, IWebMessage> WebPool { get; init; } = default!;
    [Inject] private IMongoDatabase Database { get; init; } = default!;
    [Inject] private ISnackbar Snackbar { get; init; } = default!;
    [Inject] private IMemoryBus Bus { get; init; } = default!;
    [Inject] private NavigationManager NavigationManager { get; init; } = default!;

    private string Title { get; set; } = Global.Name;

    private readonly string _id = ObjectId.GenerateNewId().ToString();
    private readonly List<BreadcrumbItem> _breadcrumbs = new();
    private readonly IndexViewModel _model = new();
    private readonly List<IDisposable> _subscriptions = new();

    protected override async Task OnInitializedAsync()
    {
        _subscriptions.Add(Bus.SubscribeAsync<ConsoleQueryProxy>(OnQueryResultAsync, p => p.Id == _id));
    }

    private async Task LoadDataAsync()
    {
        _breadcrumbs.Clear();

        _breadcrumbs.Add(new BreadcrumbItem("Home", href: Navigation.Home));
        _breadcrumbs.Add(new BreadcrumbItem("Hosts", href: Navigation.Management.Hosts.Index));

        StateHasChanged();

        if (string.IsNullOrWhiteSpace(HostId) || ObjectId.TryParse(HostId, out var hostId) is false)
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Management.Hosts.Index);
            return;
        }

        var host = await Database.Host()
            .Find(Builders<HostEntity>
            .Filter
            .Eq(p => p.Id, HostId))
            .FirstOrDefaultAsync(default);

        if (host is null)
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Management.Hosts.Index);
            return;
        }

        Title = $"Hosts » {host.Name} » Actions » Console｜Insight";

        _breadcrumbs.Add(new BreadcrumbItem(host.Name, href: Navigation.Management.Hosts.DetailsHref(HostId)));
        _breadcrumbs.Add(new BreadcrumbItem("Console", href: "#", true));

        StateHasChanged();
    }

    private async Task SubmitAsync()
    {
        if (_model.ConsoleQuery.Query is null || WebPool.Any() is false) return;

        try
        {
            await WebPool.First().Value.SendAsync(new ConsoleQueryProxyRequest
            {
                Id = _id,
                HostId = HostId,
                Query = _model.ConsoleQuery.Query
            }, default);

            Notification.Information(Snackbar, "Sent Query Command");
        }
        catch (Exception ex)
        {
            Notification.Error(Snackbar, ex.Message);
        }
    }

    private async ValueTask OnQueryResultAsync(ConsoleQueryProxy query, CancellationToken cancellationToken)
    {
        _model.ConsoleQuery.HadErrors = query.HadErrors;
        _model.ConsoleQuery.Data = query.Data;
        _model.ConsoleQuery.Errors = query.Errors;

        await InvokeAsync(StateHasChanged);
    }

    private class IndexViewModel
    {
        public readonly ConsoleQueryProxy ConsoleQuery = new();
    }
}