using UnityEngine;

public class SharkSpawner : Spawner
{
    public GameObject sharkPrefab;

    public SpriteRenderer gameBoardSpriteRenderer;

    private Bounds gameBoardBounds;

    private float spawnTimer = 0f;

    private Vector2 spawnPosition;

    private bool isActive = true;

    private static float spawnProbability = 0.05f;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        gameBoardBounds = gameBoardSpriteRenderer.bounds;
        Reset();
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        spawnTimer += Time.fixedDeltaTime;

        if (spawnTimer >= 1f && isActive && isSpawning)
        {
            spawnTimer = 0f;
            if (Random.value < spawnProbability)
            {
                GameObject shark = Instantiate(sharkPrefab, spawnPosition, Quaternion.identity);
                Shark sharkScript = shark.GetComponent<Shark>();
                sharkScript.gameBoardSpriteRenderer = gameBoardSpriteRenderer;
                sharkScript.player = FindAnyObjectByType<Player>();
                isActive = false;
            }
        }
    }

    public void Reset()
    {
        isActive = true;
        spawnTimer = 0f;

        Vector2 boardCenter = gameBoardBounds.center;
        Vector2 spawnAreaSize = gameBoardBounds.size * (2f / 3f);
        Vector2 halfSpawnArea = spawnAreaSize * 0.5f;

        spawnPosition = new Vector2(
            Random.Range(
                boardCenter.x - halfSpawnArea.x,
                boardCenter.x + halfSpawnArea.x
            ),
            Random.Range(
                boardCenter.y - halfSpawnArea.y,
                boardCenter.y + halfSpawnArea.y
            )
        );
    }
}
