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

public class AstroidSpawner : MonoBehaviour
{
    public GameObject GravityObject;
    public float Distance = 10;
    public GameObject SpawnPrefab;
    public int MinSpawnCount = 1;
    public int MaxSpawnCount = 3;
    public float SpawnDelay = 1f;
    private float currentSpawnDelay = 0;

    public void Start()
    {
        if (GravityObject == null)
        {
            GravityObject = GameObject.FindWithTag("GravitySource");
        }

        currentSpawnDelay = SpawnDelay;
    }

    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.white;
        Gizmos.DrawWireSphere(GravityObject.transform.position, Distance);
    }

    public void Update()
    {
        currentSpawnDelay -= Time.deltaTime;

        if(currentSpawnDelay <0)
        {
            Spawn();
        }
    }

    private void Spawn()
    {
        currentSpawnDelay = SpawnDelay;
        int spawnCount = UnityEngine.Random.Range(MinSpawnCount, MaxSpawnCount);

        for (int i = 0; i < spawnCount; i++)
        {
            var direction = Quaternion.Euler(UnityEngine.Random.Range(-180.0f, 180.0f), UnityEngine.Random.Range(-180.0f, 180.0f), UnityEngine.Random.Range(-180.0f, 180.0f)) * Vector3.up;
            var astroid = GameObject.Instantiate(SpawnPrefab);
            astroid.transform.position = GravityObject.transform.position + direction * Distance;
            var childControllers = astroid.GetComponentsInChildren<GravityController>();
            foreach(var con in childControllers)
            {
                con.GravityObject = GravityObject;
            }

            astroid.GetComponent<GravityController>().GravityObject = this.GravityObject;
            astroid.GetComponent<EffectSpawner>().GravityObject = this.GravityObject;
        }
    }
}
