using Insight.Infrastructure;
using Insight.Infrastructure.Entities;
using Insight.Web.Constants;
using Microsoft.AspNetCore.Components;
using MongoDB.Bson;
using MongoDB.Driver;
using MudBlazor;

namespace Insight.Web.Pages.Management.Hosts.Systems.VirtualMaschines;

[Route(Navigation.Management.Hosts.Systems.VirtualMaschines.Details)]
public partial class Details
{
    [Parameter] public string? HostId { get; set; }
    [Parameter] public string? VirtualMaschineId { get; set; }

    [Inject] private IMongoDatabase Database { get; init; } = default!;
    [Inject] private ISnackbar Snackbar { get; init; } = default!;
    [Inject] private NavigationManager NavigationManager { get; init; } = default!;

    private string Title { get; set; } = Global.Name;
    private List<BreadcrumbItem> Breadcrumbs { get; } = new();
    private HostHypervisorVirtualMaschineEntity? HostVirtualMaschine { get; set; }
    private HashSet<TreeItemData> TreeItems { get; set; } = new HashSet<TreeItemData>();

    private async Task LoadDataAsync()
    {
        Breadcrumbs.Clear();
        HostVirtualMaschine = null;
        TreeItems.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;
        }

        Breadcrumbs.Add(new BreadcrumbItem(host.Name, href: Navigation.Management.Hosts.DetailsHref(HostId)));
        Breadcrumbs.Add(new BreadcrumbItem("Virtual Maschines", href: Navigation.Management.Hosts.Systems.VirtualMaschines.IndexHref(HostId)));

        StateHasChanged();

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

        HostVirtualMaschine = await Database.HostHypervisorVirtualMaschine()
            .Aggregate()
            .Match(p => p.Host == HostId && p.Id == VirtualMaschineId)
            .Lookup<HostHypervisorVirtualMaschineEntity, HostHypervisorVirtualMaschineConfigEntity, HostHypervisorVirtualMaschineEntity>(Database.HostVirtualMaschineConfig(), p => p.Id, p => p.VirtualMaschine, p => p.Configs)
            .FirstOrDefaultAsync();

        if (HostVirtualMaschine is null)
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Management.Hosts.Systems.VirtualMaschines.IndexHref(HostId));
            return;
        }

        Title = $"Hosts » {host.Name} » Virtual Maschine » {HostVirtualMaschine.Name}｜Insight";

        Breadcrumbs.Add(new BreadcrumbItem(HostVirtualMaschine.Name, href: "#", true));

        StateHasChanged();

        // build snapshot tree
        BuildSnapshotTree();

        StateHasChanged();
    }

    private void BuildSnapshotTree()
    {
        if (HostVirtualMaschine?.Configs is null) return;

        foreach (var config in HostVirtualMaschine.Configs.Where(p => string.IsNullOrWhiteSpace(p.ParentId)))
        {
            var item = new TreeItemData(config);

            if (config?.UniqueId == HostVirtualMaschine?.UniqueId)
            {
                item.IsCurrentConfig = true;
            }

            TreeItems.Add(item);
            Recursive(item, config);
        }

        StateHasChanged();
    }

    private void Recursive(TreeItemData item, HostHypervisorVirtualMaschineConfigEntity entity)
    {
        var childs = HostVirtualMaschine?.Configs?.Where(p => p.ParentId == entity.UniqueId);

        if (childs is not null && childs.Any())
        {
            item.TreeItems = new HashSet<TreeItemData>();

            foreach (var child in childs.OrderBy(p => p.CreationTime))
            {
                var newItem = new TreeItemData(child);

                if (child?.UniqueId == HostVirtualMaschine?.UniqueId)
                {
                    newItem.IsCurrentConfig = true;
                }

                item.TreeItems.Add(newItem);
                Recursive(newItem, child);
            }
        }
    }

    public class TreeItemData
    {
        public HostHypervisorVirtualMaschineConfigEntity Entity { get; set; }
        public bool IsCurrentConfig { get; set; } = false;

        public bool IsExpanded { get; set; } = true;
        public bool HasChild => TreeItems != null && TreeItems.Count > 0;
        public HashSet<TreeItemData> TreeItems { get; set; } = new HashSet<TreeItemData>();

        public TreeItemData(HostHypervisorVirtualMaschineConfigEntity entity)
        {
            Entity = entity;
        }
    }
}