using Fantasy;
using Fantasy.Async;
using Fantasy.Network.Interface;

namespace NB.Chat;

/// <summary>
/// 请求进入频道
/// </summary>
public class
    C2S_JoinChannelRequestHandler : RouteRPC<SocialUnit, C2S_JoinChannelRequest, S2C_JoinChannelResponse>
{
    protected override async FTask Run(SocialUnit entity, C2S_JoinChannelRequest request,
        S2C_JoinChannelResponse response, Action reply)
    {
        if (request.Target < 1)
        {
            response.ErrorCode = ErrorCode.ErrArgs;
            return;
        }

        var channelCenter = entity.Scene.GetComponent<ChatChannelCenterComponent>();
        if (channelCenter == null)
        {
            response.ErrorCode = ErrorCode.ErrServer;
            return;
        }

        var oldChannelId = entity.CurrentChannel;
        if (oldChannelId > 0)
        {
            //退出旧的频道
            var oldChannel = await channelCenter.Get(oldChannelId);
            if (oldChannel != null)
            {
                oldChannel.Exit(entity);
            }
        }

        //加入新频道
        var newChannel = await channelCenter.Get(request.Target);
        if (newChannel != null)
        {
            if (newChannel.ChannelType == 1)
            {
                //工会频道需要再工会才能加入
            }
            else if (newChannel.ChannelType == 0)
            {
                //地图频道需要判断在这个地图才能加入
            }

            newChannel.Enter(entity);
        }
        else
        {
            response.ErrorCode = ErrorCode.ChatNotChannel;
        }
    }
}