using System;
using System.Collections;
using System.Linq;
using TMPro;
using UniRx;
using UnityEngine;
using Random = UnityEngine.Random;

public class CornHarvester : MonoBehaviour
{
    [SerializeField] private TextMeshPro cornCounter;
    [SerializeField] private GameObject harvestedPrefab;
    [SerializeField] private float thrust = 100f;
    private float duration = .5f;
    private int maxCorn = 100; // 収穫演出で出るコーンの数を制限
    private string counterFormat = "{0}";
    private Coroutine animationCoroutine;

    private readonly ReactiveProperty<int> count = new ReactiveProperty<int>(0);
    
    private void Start()
    {
        count.AddTo(this);
        cornCounter.text = "0";
        count
            .BatchFrame()
            .Select(x => x.Last())
            .Pairwise()
            .Subscribe(x =>
        {
            this.SafeStopCoroutine(animationCoroutine);
            animationCoroutine =  this.CallLerpSmooth(duration, lerp => {
                cornCounter.text = string.Format(counterFormat,  (int)Mathf.Lerp(x.Previous, x.Current, lerp));
            });

            StartCoroutine(Harvested(Mathf.Min(maxCorn, x.Current - x.Previous)));
        }).AddTo(this);
    }

    private IEnumerator Harvested(int cnt)
    {
        for (int i = 0; i < cnt; i++)
        {
            var corn = Instantiate(harvestedPrefab, cornCounter.transform.position, Quaternion.identity);
            corn.GetComponent<Rigidbody2D>().AddForce(new Vector2(Random.Range(-0.3f, 0.3f), -1).normalized * thrust, ForceMode2D.Impulse);
            yield return null;
        }
    }

    public void AddCount(int value)
    {
        count.Value += value;
    }
}
