using Fantasy;
using Fantasy.Async;

namespace NB.Game;

public static class PlayerWalletComponentSystem
{
    #region Save

    public static async FTask Save(this PlayerWalletComponent self)
    {
        await self.Scene.World.DataBase.Save(self);
    }

    #endregion


    #region Add & Sub

    /// <summary>
    /// 货币是否足够
    /// </summary>
    /// <param name="self"></param>
    /// <param name="configId"></param>
    /// <param name="count"></param>
    /// <returns></returns>
    public static bool Have(this PlayerWalletComponent self, uint configId, int count)
    {
        if (self.Currency.TryGetValue(configId, out var value))
        {
            if (value >= Math.Abs(count))
            {
                return true;
            }
        }

        return false;
    }

    public static async FTask Add(this PlayerWalletComponent self, uint configId, int count)
    {
        if (count < 1)
        {
            Log.Error("Wallet Add Count Error ");
            return;
        }

        if (!self.Currency.TryAdd(configId, count))
        {
            self.Currency[configId] += count;
        }

        await self.Save();
    }

    public static async FTask Sub(this PlayerWalletComponent self, uint configId, int count)
    {
        if (count > 0)
        {
            Log.Error("Wallet Sub Count Error ");
            return;
        }

        if (self.Currency.TryGetValue(configId, out var value))
        {
            if (value >= Math.Abs(count))
            {
                self.Currency[configId] += count;
                await self.Save();
            }
            else
            {
                Log.Error("Wallet Sub Count Error Lower");
            }
        }
        else
        {
            Log.Error("Wallet Sub Count Error Not");
        }
    }

    #endregion
}