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

public class SpookyNumber
{
    public SpookyNumber()
    {
        Seed = Random.value * 1337.7f;
        lifetime = 5.0f + Random.value * 3.0f;
    }
    public Vector3 m_RootPosition;
    public SpriteRenderer m_SpriteRenderer;
    public float Seed;
    public float lifetime = 5.0f;
}

public class NumberRenderer : MonoBehaviour
{
    [SerializeField] private SpriteRenderer m_SpritePrefab;
    public Sprite[] m_NumberSprites;
    private List<SpookyNumber> m_Numbers = new List<SpookyNumber>();

    public void RefreshNumbers(int[] numbers, Vector2Int[] positions)
    {
        for(int i = 0; i < numbers.Length; i++)
        {
            SpookyNumber sp = new SpookyNumber();
            sp.m_SpriteRenderer = Instantiate<SpriteRenderer>(m_SpritePrefab);
            sp.m_SpriteRenderer.transform.parent = transform;
            sp.m_RootPosition = sp.m_SpriteRenderer.transform.position = (Vector2)(positions[i]);
            sp.m_SpriteRenderer.sprite = m_NumberSprites[numbers[i]];
            m_Numbers.Add(sp);
        }
    }

    // Start is called before the first frame update
    void Start()
    {
        
    }

    private void Update()
    {
        if (m_Numbers.Count > 0)
        {
            for (int i = 0; i < m_Numbers.Count; i++)
            {
                m_Numbers[i].m_SpriteRenderer.transform.position = m_Numbers[i].m_RootPosition + new Vector3(Mathf.PerlinNoise(m_Numbers[i].Seed + Time.time, 0f), Mathf.PerlinNoise( 0f, m_Numbers[i].Seed + Time.time), 0.0f) * 0.1f;
                m_Numbers[i].lifetime -= Time.deltaTime;
                if (m_Numbers[i].lifetime < 1)
                {
                    Color c = m_Numbers[i].m_SpriteRenderer.color;
                    c.a = m_Numbers[i].lifetime;
                    m_Numbers[i].m_SpriteRenderer.color = c;
                }
                if (m_Numbers[i].lifetime < 0)
                {
                    Destroy(m_Numbers[i].m_SpriteRenderer.gameObject);
                    m_Numbers.RemoveAt(i);
                    i--;
                }
            }
        }
    }
}
