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

public class CoinManager : SingletonMonoBehaviour<CoinManager>
{
    // 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)
    {
        ownCoin += count;
        // 生成枚数決定
        var spawnCount = Mathf.Min(count, 7);
        // 生成ポジション決め、生成
        InstantiateEffeect(coinPrefab, spawnCount, Vector3.zero, coinIconTransform.position, () =>
        {
            coinCountText.CountUpAnimation(coinTextFormat, ownCoin, duration + spawnCount * 0.1f);
            callback.Invoke();
        });
    }

    private void InstantiateEffeect(RectTransform prefab, int count, Vector3 from, Vector3 to, Action callback)
    {
        var baseAngle = UnityEngine.Random.value * 360.0f;
        var angle = -360.0f / count;
        //コインアニメーション 
        for(int i = 0; i < count; ++i){
            var index = i;
            // 円状にバラけてた位置を生成
            var tempPosition = from + (Vector3)Vector2.up.RotateDeg(baseAngle + i * angle + angle * UnityEngine.Random.value * 0.5f) * (0.2f + UnityEngine.Random.value * 0.8f);
            // 0.1秒ごとにコインを生成
            this.CallWaitForSeconds(index * 0.1f, () => {
                var effect = Instantiate(prefab, tempPosition, Quaternion.identity, rootTransform);
                // 表示から1秒経ったら0.2秒かけてコイン表示部分に飛んでいく
                this.CallWaitForSeconds(1.0f, () => {
                    this.CallLerp(0.2f, t => {
                        effect.position = Vector3.Lerp(tempPosition, to, t * t);
                    }, () => {
                        // コインが到着したらSEとバイブ再生。コインはずみアニメーションを再生
                        VibrationManager.Instance.PlayVibrationOnceWeak();
                        coinAnimator.SetTrigger("Add");
                        SoundManager.Instance.PlaySE("se_coin_count");
                        // コインは削除
                        Destroy(effect.gameObject);
                    });
                });
            });
        }
        this.CallWaitForSeconds(1.0f + 0.2f, callback);
    }
}
