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;
    [SerializeField] private GameEventListener onJoinedRoom;
    [SerializeField] private GameEventListener_JobInstance onJobCompleted;

    public int currentCoin;

    CoinData coinData = new CoinData();

    #region Singleton
    private static CoinBag _instance;

    // Public reference to the singleton instance
    public static CoinBag Instance
    {
        get
        {
            // If the instance doesn't exist, try to find it in the scene
            if (_instance == null)
            {
                _instance = FindObjectOfType<CoinBag>();
            }
            return _instance;
        }
    }
    #endregion

    private void Awake()
    {
        onCoinDrop.Response.AddListener(ChangeAmount);

        onJoinedRoom.Response.AddListener(LoadCoins);

        onJobCompleted.Response.AddListener(job => ChangeAmount(job.coinReward));

        UpdateCoinText();
    }


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

        SaveCoinData();

        UpdateCoinText();
    }

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

        currentCoin -= amount;

        SaveCoinData();

        UpdateCoinText();
    }

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

        else return true;
    }

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

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

        PlayerDataHandler.Instance.SavePlayerCoinData(PlayerDataHandler.Instance.currentPlayerName.Value, coinData);

    }

    private void LoadCoins()
    {
        coinData = PlayerDataHandler.Instance.LoadPlayerCoinData(PlayerDataHandler.Instance.currentPlayerName.Value);
        if (coinData != null)
        {
            Debug.Log("Success Loading CoinData");
            currentCoin = coinData.totalCoin;
            UpdateCoinText();
        }
        else
            coinData = new CoinData();
    }
}
