using Photon.Pun;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;

public class CoinBag : MonoBehaviour
{
    [SerializeField] private TMP_Text coinText;
    [SerializeField] private GameEventListener_Int onCoinDrop;

    public int currentCoin;

    CoinData coinData = new CoinData();
    string playerCoinKey;

    private void Awake()
    {
        playerCoinKey = GameConstants.PlayerPrefsKeys.GetPlayerCoinKey(PhotonNetwork.NickName);

        if (GameStatePersistenceManager.Instance.HasDataForKey(playerCoinKey))
        {
            coinData = GameStatePersistenceManager.Instance.LoadData<CoinData>(playerCoinKey);
            currentCoin = coinData.totalCoin;
        }
        else
            currentCoin = 0;

        onCoinDrop.Response.AddListener(ChangeAmount);

        UpdateCoinText();
    }


    public void ChangeAmount(int amount)
    {
        currentCoin += amount;

        SaveCoinData();

        UpdateCoinText();
    }

    public bool SpendCoin(int amount)
    {
        if (currentCoin - amount < 0)
            return false;

        currentCoin -= amount;

        SaveCoinData();

        UpdateCoinText();
        return true;
    }

    private void UpdateCoinText()
    {
        coinText.text = currentCoin.ToString();
    }

    private void SaveCoinData()
    {
        coinData.totalCoin = currentCoin;

        GameStatePersistenceManager.Instance.SaveData(playerCoinKey, coinData);

    }
}
