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

public class GameManager : MonoBehaviour
{
    public int currency;
    public float timeLeft;

    System.Random random = new System.Random();

    private TextMeshProUGUI soulsLeft;
    private TextMeshProUGUI wallet;
    private TextMeshProUGUI timeDisp;

    public List<GameObject> rooms = new List<GameObject>();
    public GameObject spawnRoom;
    public GameObject furnacePrefab;
    public int roomCount = 0;
    public int maxRooms = 10;
    public bool GenerationComplete = false;
    public bool furnaceSpawned = false;
    public GameObject shopUI;

    public List<GameObject> furnaceSpawnpoints = new List<GameObject>();

    // Start is called before the first frame update
    void Start()
    {
        soulsLeft = GameObject.Find("Canvas/Soul Counter").GetComponent<TextMeshProUGUI>();
        wallet = GameObject.Find("Canvas/Wallet/Currency Display").GetComponent<TextMeshProUGUI>();
        timeDisp = GameObject.Find("Canvas/Timer").GetComponent<TextMeshProUGUI>();
        GenerateMap();
    }

    public void GenerateMap()
    {
        furnaceSpawned = false;
        roomCount = 0;
        GameObject room = Instantiate(spawnRoom);
        room.transform.position = new Vector3(0, 0, 0);
    }

    public int Random(int max = 10)
    {
        return random.Next(0, max);
    }

    public void SpawnFurnace()
    {
        GameObject furnace = Instantiate(furnacePrefab);
        furnace.transform.position = furnaceSpawnpoints[random.Next(0, furnaceSpawnpoints.Count)].transform.position;
        furnace.GetComponentsInChildren<ShopOpener>()[0].shopUI = shopUI;
        furnaceSpawned = true;
    }

    // Update is called once per frame
    void Update()
    {
        string remainingSouls = GameObject.FindGameObjectsWithTag("Soul").Length.ToString();
        if (GameObject.FindGameObjectsWithTag("Soul").Length > 0)
        {
            soulsLeft.text = "Souls Left:\n" + remainingSouls;
        }
        else
        {
            soulsLeft.text = "Souls Found!\nFind The Exit!";
        }
        if (timeLeft > 0)
        {
            timeLeft -= Time.deltaTime;
            timeDisp.text = ((int)timeLeft + 1).ToString();
        }
        wallet.text = currency.ToString();
        if (GenerationComplete && !furnaceSpawned)
        {
            SpawnFurnace();
        }
    }
}
