using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.Serialization;
using UnityEngine.UI;

public class UIItemSpawner : MonoBehaviour
{
    [FormerlySerializedAs("EntityToSpawn")] public GameObject entityToSpawn ;
    [FormerlySerializedAs("MaxNumberOfInstances")] public int maxNbEntityInstances ;
    [FormerlySerializedAs("InitNumberOfInstances")] public int initNbEntityInstances ;

    private GameObject[] _instances;
    private  int index = 0 ;
    private  int gap = 25 ;
    
    // Animation
    public Sprite[] m_SpriteArray;
    
    public Sprite[] m_AltSpriteArray;

    private bool toggleAlt = false;

    private float normalSpeed = .07f;
    private float altSpeed = .03f;
    private float m_Speed ;
    private int m_IndexSprite;
    private Image[] _images;
    Coroutine m_CorotineAnim;
    void Start()
    
    {
        _instances = new GameObject[maxNbEntityInstances];
        _images = new Image[maxNbEntityInstances];
        for (int index = 0; index < initNbEntityInstances; index++)
        {
            SpawnEntity() ;
        }
        
        m_Speed = normalSpeed;
        StartCoroutine(PlayAnimUI());
         
    }
    public void SpawnEntity()
    {
        if (index >= maxNbEntityInstances)
            return;
        var currentPos = gameObject.transform.position;
        gameObject.transform.position = new Vector3(currentPos.x + gap, currentPos.y, currentPos.z);
        _instances[index] = Instantiate(entityToSpawn, transform.parent, true);
        _images[index] = _instances[index].GetComponent<Image>();
        _instances[index].transform.position = currentPos;
        index++;
    }
    
    public void DespawnEntity()
    {
        Debug.Log(index);
        if (index <= 0)
            return;
        var currentPos = gameObject.transform.position;
        gameObject.transform.position = new Vector3(currentPos.x - gap, currentPos.y, currentPos.z); ;
        index--;
        Destroy(_instances[index]);
    }

    public void SetAltItem(bool alt)
    {
        toggleAlt = alt;
        m_Speed = alt ? altSpeed : normalSpeed;
        Debug.Log(m_Speed);
    }

    IEnumerator PlayAnimUI()
    {
        yield return new WaitForSeconds(m_Speed);
        if (m_IndexSprite >= m_SpriteArray.Length)
        {
            m_IndexSprite = 0;
        }

        for (int currentIndex = 0; currentIndex < index; currentIndex++)
        {
            
            var _spriteIndex = (m_IndexSprite + maxNbEntityInstances - currentIndex) % m_SpriteArray.Length;
            Debug.Log(_spriteIndex);
            _images[currentIndex].sprite = toggleAlt ? m_AltSpriteArray[_spriteIndex] : m_SpriteArray[_spriteIndex];
        } 
         
        m_IndexSprite += 1;
        m_CorotineAnim = StartCoroutine(PlayAnimUI());
    }
}
