using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class CoinManager : SingletonMonoBehaviour<CoinManager>
{
    private static readonly int Add = Animator.StringToHash("Add");
    
    // CoinView
    [SerializeField] private RectTransform coinIconTransform;
    [SerializeField] private TextWithCountUpInt coinCountText;
    [SerializeField] private Animator coinAnimator;
    
    [SerializeField] private RectTransform coinPrefab;

    // Animation
    [SerializeField] private float duration = 0.5f;

    [SerializeField] private RectTransform rootTransform;
    private int ownCoin;
    public int OwnCoin => ownCoin;
    private string coinTextFormat = "{0}";

    void Awake(){
        if(CheckInstance()) return ;
    }

    public void ChangeCoin(int count)
    {
        ownCoin = count;
        coinCountText.ChangeValue(coinTextFormat, ownCoin);
    }

    public void AddCoin(int count)
    {
        ownCoin += count;
        coinCountText.CountUpAnimation(coinTextFormat, ownCoin, duration);
    }

    public void AddCoinWithEffect(int count, Action callback = null)
    {
        ownCoin += count;
        // 生成枚数決定
        // 生成ポジション決め、生成
        InstantiateEffeect(coinPrefab, count, Vector3.zero, coinIconTransform.position, () =>
        {
            coinCountText.CountUpAnimation(coinTextFormat, ownCoin, duration);
            callback?.Invoke();
        });
    }

    private void InstantiateEffeect(RectTransform prefab, int count, Vector3 from, Vector3 to, Action callback)
    {
        // アニメ50フレーム
        this.CallWaitForSeconds(1.0f, () => {
            // コインが到着したらSEとバイブ再生。コインはずみアニメーションを再生
            VibrationManager.Instance.PlayVibrationOnceWeak();
            coinAnimator.SetTrigger(Add);
            // SoundManager.Instance.PlaySE("se_coin_count");
            callback.Invoke();
        });
    }
    
    public void SubCoin(int coin){
        ownCoin -= coin;
        if(coinCountText.gameObject.activeInHierarchy){
            coinCountText.CountUpAnimation(coinTextFormat, ownCoin, duration);
        }else{
            coinCountText.ChangeValue(coinTextFormat, ownCoin);
        }
    }
}
