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

public class ChunkGenerator : MonoBehaviour
{
    [SerializeField] private LaneSystem LaneSystem;
    [SerializeField] private CoinPool coinPool;
    [field: SerializeField] public List<ObstaclePool> ObstaclePools { get; private set; }
    
    private bool _isFirstChunk = true;
    public Chunk Generate(Chunk chunkToFill)
    {
        if (_isFirstChunk)
        {
            _isFirstChunk = false;
            return chunkToFill;
        }
        if (!ObstaclePools.IsEmpty())
        {
            var obstaclePool = ObstaclePools.GetRandomElement();
            var obstacle = obstaclePool.Spawn();
            chunkToFill.Obstacles.Add(obstacle);
            obstacle.transform.SetParent(chunkToFill.transform, true);
            obstacle.transform.localPosition = chunkToFill.Grid.GetRandomPosition();

            if (obstacle.IsOnAllLanes)
            {
                obstacle.transform.localPosition = new Vector3(
                    LaneSystem.CenterLane * LaneSystem.LaneWidth,
                    transform.localPosition.y,
                    transform.localPosition.z
                );
            }
        }
        Coin coin = coinPool.Spawn();
        chunkToFill.Coins.Add(coin);
        coin.transform.SetParent(chunkToFill.transform, true);
        Vector3 randomPosition;
        bool isPositionValid = false;
        int laneIndex = Random.Range(0, LaneSystem.LaneCount);
        randomPosition = new Vector3(
            laneIndex * LaneSystem.LaneWidth,
            chunkToFill.Grid.GetRandomPosition().y + 1.0f,
            chunkToFill.Grid.GetRandomPosition().z
        );
        while (!isPositionValid)
        {
            isPositionValid = true;
            foreach (var obstacle in chunkToFill.Obstacles)
            {
                if (Vector3.Distance(randomPosition, obstacle.transform.localPosition) < 1.0f)
                {
                    isPositionValid = false;
                    break;
                }
            }
            if (!isPositionValid)
            {
                randomPosition = new Vector3(
                    laneIndex * LaneSystem.LaneWidth,
                    chunkToFill.Grid.GetRandomPosition().y + 1.0f, 
                    chunkToFill.Grid.GetRandomPosition().z
                );
            }
        }
        coin.transform.localPosition = randomPosition;
        coin.UpdateStartPositionForSinAnimator();
        return chunkToFill;
    }
}
