using Fantasy.Async;
using Fantasy.Entitas;
using Fantasy.Entitas.Interface;
using Fantasy.Helper;

namespace NB.Chat;

public class ChatChannelCenterComponentAwakeSystem : AwakeSystem<ChatChannelCenterComponent>
{
    protected override void Awake(ChatChannelCenterComponent self)
    {
    }
}

public class ChatChannelCenterComponentDestroySystem : DestroySystem<ChatChannelCenterComponent>
{
    protected override void Destroy(ChatChannelCenterComponent self)
    {
        self.Channels.Clear();
    }
}

public static class ChatChannelCenterComponentSystem
{
    /// <summary>
    /// 获取一个频道
    /// </summary>
    /// <param name="self"></param>
    /// <param name="channelId"></param>
    /// <returns></returns>
    public static async FTask<ChatChannel?> Get(this ChatChannelCenterComponent self, long channelId)
    {
        if (self.Channels.TryGetValue(channelId, out var channel))
        {
            return channel;
        }

        //查数据库
        channel = await self.Scene.World.DataBase.Query<ChatChannel>(channelId, true);
        if (channel != null)
        {
            self.Channels.Add(channel.Id, channel);
        }

        return channel;
    }

    /// <summary>
    /// 申请创建一个频道
    /// </summary>
    /// <param name="self"></param>
    /// <param name="unit"></param>
    /// <returns></returns>
    public static async FTask<ChatChannel> Create(this ChatChannelCenterComponent self, SocialUnit unit)
    {
        var channel = Entity.Create<ChatChannel>(self.Scene, true, true);
        channel.Creator = unit.Role.RoleId;
        channel.CreateTime = TimeHelper.Now;
        self.Channels.Add(channel.Id, channel);
        //保存到数据库
        await self.Scene.World.DataBase.Save(channel);

        return channel;
    }


    /// <summary>
    /// 解散
    /// </summary>
    /// <param name="self"></param>
    /// <param name="channelId"></param>
    public static void Disband(this ChatChannelCenterComponent self, long channelId)
    {
        if (self.Channels.Remove(channelId, out var channel))
        {
            return;
        }

        channel?.Dispose();
    }
}