using Insight.Domain.Network;
using Insight.Domain.Network.Agent.Messages;
using Insight.Infrastructure.Entities;
using Insight.Web.Constants;
using Insight.Web.Network.Broker;
using Microsoft.AspNetCore.Components;
using MongoDB.Bson;
using MongoDB.Driver;
using MudBlazor;
using System.Diagnostics;
using System.Threading;
using Vaitr.Bus;
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 ISessionPool<WebSession, IMessage> WebPool { get; init; } = default!;
    [Inject] private IMongoDatabase Database { get; init; } = default!;
    [Inject] private ISnackbar Snackbar { get; init; } = default!;
    [Inject] private Bus 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 ViewModel _model = new();

    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 OnRefreshAsync(ConsoleOptionDialog.ScriptItem item)
    {
        _model.Request.RequestData = item.Value;

        await InvokeAsync(StateHasChanged);
    }

    private async Task RunAsync(CancellationToken cancellationToken = default)
    {
        if (_model.Request.RequestData is null)
        {
            Notification.Error(Snackbar, "Invalid Request Data");
            return;
        }

        if (WebPool.Any() is false)
        {
            Notification.Error(Snackbar, "Client unreachable");
            return;
        }

        try
        {
            _running = true;

            var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
            var timeoutTask = Task.Delay(TimeSpan.FromSeconds(30), timeoutCts.Token);

            // subscribe response
            using var token = Bus.SubscribeAsync<Proxy<Response>>(async (response, ctc) =>
            {
                _model.Response.ResponseError = response.Message?.ResponseError;
                _model.Response.ResponseData = response.Message?.ResponseData;

                timeoutCts.Cancel();

                _activeWindow = 1;

                await InvokeAsync(StateHasChanged);
            }, p => p.Message?.RequestId == _id);

            // send request
            await WebPool.First().Value.SendAsync(new Proxy<Request>
            {
                ProxyId = HostId,
                Message = new Request
                {
                    RequestId = _id,
                    RequestData = _model.Request.RequestData
                }
            }, default);

            Notification.Information(Snackbar, "Sent Script...");

            await Task.WhenAny(timeoutTask);
        }
        catch (Exception ex)
        {
            Notification.Error(Snackbar, ex.Message);
        }
        finally
        {
            _running = false;
        }
    }

    private class ViewModel
    {
        public readonly Request Request = new();
        public readonly Response Response = new();
    }
}