using System.Collections;
using System.Collections.Generic;
using TMPro.Examples;
using Unity.VisualScripting;
using UnityEngine;

public class GenerateOrbs : MonoBehaviour
{
    public GameObject orb;
    [SerializeField] int spawnRadius;
    [SerializeField] int maximumOrbs;

    public void StartGenerating(Transform playerTransform)
    {
        StartCoroutine(GenerateOrb(playerTransform));
    }

    IEnumerator GenerateOrb(Transform playerTransform)
    {
        int spawnedOrbCounter = 0;

        while (spawnedOrbCounter < maximumOrbs)
        {
            float spawnX = Random.Range(-spawnRadius, spawnRadius) + playerTransform.position.x;
            float spawnZ = Random.Range(-spawnRadius, spawnRadius) + playerTransform.position.z;
            Vector3 rayOrigin = new Vector3(spawnX, 500f, spawnZ);

            if(Physics.Raycast(rayOrigin, Vector3.down, out RaycastHit hit, 1000f)){
                if (hit.collider.CompareTag("Floor"))
                {
                    Vector3 spawnPosition = hit.point + new Vector3(0, 1f, 0);
                    GameObject orbObject = Instantiate(orb, spawnPosition, Quaternion.identity);
                    spawnedOrbCounter++;

                    yield return null;
                }

                if (spawnedOrbCounter < maximumOrbs)
                {
                    yield return null;
                }

                Debug.Log("All orbs successfully spawned!");
            }
            else
            {
                Debug.DrawRay(rayOrigin, Vector3.down * 1000f, Color.red, 5f);
                Debug.Log($"No hit at {spawnX}, {spawnZ}");
            }
        }
    }
}
