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

/// <summary>
/// Class for dealing with the spawning of basic enemies
/// </summary>
public class BasicEnemySpawning : ObjectSpawning
{
    public GameObject enemyPrefab;
    public EnemyTypeName spawnersEnemyType;

    private void Awake()
    {
        _spawnedObject = enemyPrefab;
    }

    /// <summary>
    /// Reduce the spawned counter for this spawner
    /// </summary>
    public override void ReduceSpawnedCount()
    {
        objectCount = Mathf.Clamp(objectCount - 1, 0, _numberToSpawn);
        base.ReduceSpawnedCount();
    }

    /// <summary>
    /// Spawn the gameObject assigned to this spawner
    /// </summary>
    protected override void DoASpawn()
    {
        float xPos = Random.Range(-xSpawnRange, xSpawnRange);
        float yPos = Random.Range(-ySpawnRange, ySpawnRange);
        float zPos = Random.Range(-zSpawnRange, zSpawnRange);

        // If debug is checked then try to spawn the object above the player, this is to test collisions
        if (debugSpawn)
        {
            GameObject currentPlayer = GameObject.Find("Player");
            xPos = currentPlayer.transform.position.x;
            zPos = currentPlayer.transform.position.z;
            yPos = currentPlayer.transform.position.y + 10;
        }        
        
        GameObject newSpawn = Instantiate(_spawnedObject);
        // Set the start height of the gameObject from the blackhole
        HoverMovement newSpawnMovement = newSpawn.GetComponent<HoverMovement>();
        if (newSpawnMovement)
        {
            newSpawnMovement.startPositionVector = new Vector3(xPos, yPos, zPos);
            newSpawnMovement.ForceHeightAdjust(Random.Range(minSpawnHeight, maxSpawnHeight));
        }

        if (Physics.CheckSphere(newSpawn.transform.position, 2.0f, LayerMask.NameToLayer("Player")))
        {
            xPos = Random.Range(-xSpawnRange, xSpawnRange);
            yPos = Random.Range(-ySpawnRange, ySpawnRange);
            zPos = Random.Range(-zSpawnRange, zSpawnRange);
            newSpawnMovement.startPositionVector = new Vector3(xPos, yPos, zPos);
            newSpawnMovement.ForceHeightAdjust(Random.Range(minSpawnHeight, maxSpawnHeight));
        }

        // Set the spawned to this on the gameObject
        EnemyObjectShared newSpawnShared = newSpawn.GetComponent<EnemyObjectShared>();
        if (newSpawnShared)
        {
            newSpawnShared.Spawner = this;
            newSpawnShared.enemyTypeName = spawnersEnemyType;
        }

        newSpawn.SetActive(true);

        objectCount++;
        base.DoASpawn();        
    }

    protected override void GetCurrentCount()
    {
        _numberToSpawn = GameManager.Instance.GetCurrentLevelEnemyTypeCount(spawnersEnemyType);
        base.GetCurrentCount();
    }
}
