using SharpChat.SockChat.S2CPackets;
using System.Text;

namespace SharpChat.ClientCommands;

public class WhoClientCommand : ClientCommand {
    public bool IsMatch(ClientCommandContext ctx) {
        return ctx.NameEquals("who");
    }

    public async Task Dispatch(ClientCommandContext ctx) {
        long msgId = ctx.Chat.RandomSnowflake.Next();
        StringBuilder whoChanSB = new();
        string? whoChanStr = ctx.Args.FirstOrDefault();

        if(string.IsNullOrEmpty(whoChanStr)) {
            foreach(User whoUser in ctx.Chat.Users) {
                whoChanSB.Append(@"<a href=""javascript:void(0);"" onclick=""UI.InsertChatText(this.innerHTML);""");

                if(whoUser == ctx.User)
                    whoChanSB.Append(@" style=""font-weight: bold;""");

                whoChanSB.Append('>');
                whoChanSB.Append(whoUser.LegacyName);
                whoChanSB.Append("</a>, ");
            }

            if(whoChanSB.Length > 2)
                whoChanSB.Length -= 2;

            await ctx.Chat.SendTo(ctx.User, new CommandResponseS2CPacket(msgId, LCR.USERS_LISTING_SERVER, false, whoChanSB));
        } else {
            Channel? whoChan = ctx.Chat.Channels.FirstOrDefault(c => c.NameEquals(whoChanStr));

            if(whoChan is null) {
                await ctx.Chat.SendTo(ctx.User, new CommandResponseS2CPacket(msgId, LCR.CHANNEL_NOT_FOUND, true, whoChanStr));
                return;
            }

            if(whoChan.Rank > ctx.User.Rank || (whoChan.HasPassword && !ctx.User.Can(UserPermissions.JoinAnyChannel))) {
                await ctx.Chat.SendTo(ctx.User, new CommandResponseS2CPacket(msgId, LCR.USERS_LISTING_ERROR, true, whoChanStr));
                return;
            }

            foreach(User whoUser in ctx.Chat.GetChannelUsers(whoChan)) {
                whoChanSB.Append(@"<a href=""javascript:void(0);"" onclick=""UI.InsertChatText(this.innerHTML);""");

                if(whoUser == ctx.User)
                    whoChanSB.Append(@" style=""font-weight: bold;""");

                whoChanSB.Append('>');
                whoChanSB.Append(whoUser.LegacyName);
                whoChanSB.Append("</a>, ");
            }

            if(whoChanSB.Length > 2)
                whoChanSB.Length -= 2;

            await ctx.Chat.SendTo(ctx.User, new CommandResponseS2CPacket(msgId, LCR.USERS_LISTING_CHANNEL, false, whoChan.Name, whoChanSB));
        }
    }
}