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

public class ApplePicker : MonoBehaviour
{
    [Header("Set in Inspector")]
    public GameObject basketPrefab;
    public int numBaskets = 3;
    public float basketBottomY = -14f;
    public float basketSpacingY = 2f;
    public List<GameObject> basketList;
    
    public Text roundGT;
    public Button resetButton;

    // Start is called before the first frame update
    void Start()
    {
        basketList = new List<GameObject>();
        for (int i = 0; i < numBaskets; i++) {
            GameObject tBasketGO = Instantiate<GameObject>(basketPrefab);
            Vector3 pos = Vector3.zero;
            pos.y = basketBottomY + (basketSpacingY * i);
            tBasketGO.transform.position = pos;
            basketList.Add(tBasketGO);
        }

        if (SceneManager.GetActiveScene().name == "_Scene_2") { return; }
        GameObject roundGO = GameObject.Find("RoundCounter");
        roundGT = roundGO.GetComponent<Text>();
        roundGT.text = "Round 1";
    }

    public void AppleDestroyed() {
        // Destroy all of the falling apples
        GameObject[] tAppleArray = GameObject.FindGameObjectsWithTag("Apple");
        foreach (GameObject tGO in tAppleArray) {
            Destroy(tGO);
        }
        // Destroy one of the baskets
        // Get the index of the last Basket in basketList
        int basketIndex = basketList.Count-1;
        // Get a reference to that Basket GameObject
        GameObject tBasketGO = basketList[basketIndex];
        // Remove the Basket from the list and destroy the GameObject
        basketList.RemoveAt(basketIndex);
        Destroy(tBasketGO);
        roundGT.text = "Round ";
        roundGT.text += numBaskets - basketList.Count + 1;
        // If there are no Baskets left, restart the game
        if (basketList.Count == 0) {
            GameOver();
        }
    }

    public void RottenAppleDestroyed() {
        // Destroy all of the falling apples
        GameObject[] tAppleArray = GameObject.FindGameObjectsWithTag("Apple");
        foreach (GameObject tGO in tAppleArray) {
            Destroy(tGO);
        }
        GameOver();
    }

    public void GoldenAppleDestroyed() {
        AppleTree appleTree = GameObject.FindGameObjectWithTag("AppleTree").GetComponent<AppleTree>();
        appleTree.GoldenAppleTimeStart();
    }

    public void GameOver() {
        Time.timeScale = 0;
        roundGT.text = "Game Over";
        resetButton.gameObject.SetActive(true);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}