using GraphicsManager.Objects;
using Luski.net.Structures.Public;
using OpenTK.Mathematics;

namespace Luski.GUI.MainScreen.UI.LuskiControls;

public class RoleView : FlowLayout
{
    private Label l;
    private string n = "Offline";
    public int i = 0;
    public Role? r;
    public RoleView(Role? r = null)
    {
        this.r = r;
        if (r is not null) n = r.DisplayName;
        l = new(Globals.DefaultFont)
        {
            Text = "  " + n + " — " + i,
        };
        base.Size = new(0, 30.ScaleInt());
        base.BackgroundColor = new(34, 34, 34, 255);
        Controls.Add(l);
    }

    private Dictionary<long, UserView> uuu = new();
    public List<SocketUser> Users = new();
    
    public async Task AddUser(SocketUser user, Role TopRole)
    {
        ServerProfile DefaultProfile = await user.Server.GetProfile(user.ServerProfile, CancellationToken.None);
        UserView f = await UserView.Make(user, DefaultProfile, TopRole, r is null);
        
        uuu.Add(user.Id, f);
        bool ff = false;
        for (int j = 0; j < Users.Count; j++)
        {
            if (string.Compare(DefaultProfile.DisplayName, DefaultProfile.DisplayName) > 0)
            {
                Users.Insert(j, user);
                Controls.Insert(j+1, f);
                ff = true;
                break;
            }
        }

        if (!ff)
        {
            Users.Add(user);
            Controls.Add(f);
        }
       
        Size = new(Size.X, Size.Y + f.Size.Y);
        i++;
        l.Text = "  " + n + " — " + i;
    }
    
    public void RemoveUser(long id)
    {
        Vector2i Sizes = new(Size.X, Size.Y - uuu[id].Size.Y);
        i--;
        l.Text = "  " + n + " — " + i;
        Users.Remove(uuu[id].User);
        Controls.Remove(uuu[id]);
        uuu.Remove(id);
        for (int j = 0; j < Controls.Length; j++)
        {
            ReportSizeUpdate(Controls[j]);
        }
        Size = Sizes;
    }
}