using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Dacryptero.Notifications;

namespace Dacryptero.Web.Events.Receive;

public class DatabaseConnect : ReceiveBase
{
    public string? Name { get; private set; }

    public override async Task Execute(ExecuteArgs args)
    {
        var controller = GetExistingController(args.Connection)
            // filter controller that are not in the current session
            .Where(con => args.Connection.Session.GetController(con.Config.Name) is null)
            // finish list
            .ToList();

        if (controller.Count == 0)
        {
            args.SendNotification(Notification.Error(
                "DB Connection failed",
                "No DB available to connect"
            ));
            return;
        }
        
        args.Connection.FidoLogin = new Session.Fido.PreLoginUser(
            args.Connection,
#if DEBUG
            Session.Fido.UserBase.GetConfiguration("localhost:8000"),
#else
            Session.Fido.UserBase.GetConfiguration(args.Connection.Host),
#endif
            Name,
            controller,
            false
        );

        await args.Connection.Send(new Send.LoginRequest(Name))
            .ConfigureAwait(false);
    }

    private IEnumerable<DB.DBSingleController> GetExistingController(WebSocketConnection con)
    {
        if (Name is not null)
        {
            var controller = con.DB.GetController(Name);
            if (controller is not null)
                yield return controller;
            else yield break;
        }
        else
        {
            var list = con.DB.GetCurrentController();
            for (int i = 0; i < list.Length; ++i)
                yield return list.Span[i];
        }
    }

    public override void ReadJsonContent(JsonElement json)
    {
        Name = json.GetProperty("name").GetString();
    }
}