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

public class TutorialController : MonoBehaviour
{
    public List<GameObject> _uiElements = new List<GameObject>();
    
    [SerializeField] private ComputerBehaviour _computerBehaviour;
    [SerializeField] private ObjectSO _item;

    private SellCounter[] _counters;
    
    private int _currentElement = 0;
    
    
    // Start is called before the first frame update
    private void Awake() { //Use Awake instead of Start to ensure that all the data is set before adding events
        _counters = FindObjectsOfType<SellCounter>();
        
        
        _computerBehaviour.OnBuyItem += ItemBought;
        foreach (var counter in _counters) {
            counter.OnCounterStartSelling += ItemOnSellingPedestal;
        }


    }

    private void Start() {
        _computerBehaviour.SetItem(_item, true);
    }

    private void ItemBought(object sender, System.EventArgs e) {
        _computerBehaviour.OnBuyItem -= ItemBought;
        Next();
    }
    
    private void ItemOnSellingPedestal(object sender, System.EventArgs e) {
        foreach (var counter in _counters) {
            counter.OnCounterStartSelling -= ItemOnSellingPedestal;
        }
        CustomerManager.Instance.OnCustomerLeft += CustomerLeft;
        Next();
    }
    
    private void CustomerLeft(object sender, System.EventArgs e) {
        CustomerManager.Instance.OnCustomerLeft -= CustomerLeft;
        StartCoroutine(Countdown());
        Next();
    }
    
    //20 Seconds after the customer leaves
    private IEnumerator Countdown() {
        yield return new WaitForSeconds(20);
        Next();
    }
    
    

    private void OnEnable() {
        _uiElements[_currentElement].SetActive(true);
    }

    private void Next() {
        _uiElements[_currentElement].SetActive(false);
        _currentElement++;
        if (_currentElement >= _uiElements.Count) {
            //End of tutorial
            Debug.Log("End of tutorial");
            this.gameObject.SetActive(false);
            return;
        }
        _uiElements[_currentElement].SetActive(true);
    }
    
}
