using System.Collections.Generic;
using System.Text.Json;
using Dacryptero.DB.Creation;

namespace Dacryptero.Web.Events.Send
{
    public class InfoSend : SendBase
    {
        public WebSocketConnection Connection { get; }

        public InfoSend(WebSocketConnection connection)
        {
            Connection = connection;
        }

        private void WriteDbConfigInfo(Utf8JsonWriter writer, DB.DBSingleController single,
            bool sessionMember
        )
        {
            writer.WriteStartObject();
            writer.WriteString("name", single.Config.Name);
            writer.WriteBoolean("connected", single.IsOpen && sessionMember);
            writer.WriteBoolean("hasConfidential", single.HasConfidential);
            writer.WriteString("roleSchema", single.Config.RoleSchema);
            writer.WriteStartArray("access");
            foreach (var access in single.Config.Access)
                access.WriteWebTo(writer);
            writer.WriteEndArray();
            if (Connection.UnlockedDBs.TryGetValue(single.Config.Name, out UnlockedDBInfo? info))
            {
                writer.WriteString("unlocked", info.Opened);
            }
            else writer.WriteNull("unlocked");

            writer.WriteEndObject();
        }

        protected override void WriteJsonContent(Utf8JsonWriter writer)
        {
            writer.WriteString("user", Connection.Session.Username);
            writer.WriteStartArray("database");
            var sessionMember = new HashSet<DB.DBSingleController>();
            foreach (var entry in Connection.Session.GetCurrentController().Span)
            {
                sessionMember.Add(entry);
                WriteDbConfigInfo(writer, entry, true);
            }
            foreach (var entry in Connection.DB.GetCurrentController().Span)
            {
                if (sessionMember.Contains(entry))
                    continue;
                WriteDbConfigInfo(writer, entry, false);
            }
            writer.WriteEndArray();
            writer.WriteStartArray("schemas");
            foreach (var (name, _) in Data.Schema.SchemaCollection.Schemas)
                writer.WriteStringValue(name);
            writer.WriteEndArray();
            writer.WriteString("uploadToken", Connection.Session.IdString);
        }
    }
}