public class LevelGenerator : MonoBehaviour
{
    [SerializeField] private int segmentCount = 4;
    [SerializeField] private LevelSegment[] levelSegments;

    public List<LevelSegment> currentSegments = new List<LevelSegment>();

    [Button]
    public void Generate()
    {
        Vector3 spawnPoint = Vector3.zero;
        Vector2 entryDirection = Vector2.zero;
        Vector2 exitDirection = Vector2.zero;
        List<Vector3> currentPositions = new List<Vector3>();

        LevelSegment beginSegment = Instantiate(levelSegments[Random.Range(0, levelSegments.Length)], spawnPoint, Quaternion.LookRotation(Vector3.forward));
        currentSegments.Add(beginSegment);

        exitDirection = beginSegment.GetPossibleDirections();
        Vector3 addToSpawnPoint = GetAdjustedPos(exitDirection, beginSegment);
        currentPositions.Add(spawnPoint);
        spawnPoint += addToSpawnPoint;

        for (int i = 0; i < segmentCount-1; i++)
        {
            entryDirection = -exitDirection;
            currentPositions.Add(spawnPoint);

            LevelSegment s = levelSegments[Random.Range(0, levelSegments.Length)];
            // Vector3 nextPosition = s.GetNextPosition(spawnPoint, entryDirection);
            Vector3 nextPosition = new Vector3();

            // while (!s.HasEntryDirection(entryDirection) && currentPositions.Contains(nextPosition))
            // {
            //     s = levelSegments[Random.Range(0, levelSegments.Length)];
            //     nextPosition = s.GetNextPosition(spawnPoint, entryDirection);
            // }

            while(!s.IsValid(spawnPoint, entryDirection, currentPositions))
            {
                s = levelSegments[Random.Range(0, levelSegments.Length)];
            }

            nextPosition = s.CurrentNextPosition;
            spawnPoint = nextPosition;
            spawnPoint = Vector3Int.RoundToInt(spawnPoint);

            LevelSegment segment = Instantiate(s, spawnPoint, Quaternion.Euler(Vector3.zero));

            currentSegments.Add(segment);
            exitDirection = segment.GetPossibleDirections(entryDirection);
        }

        Vector3 GetAdjustedPos(Vector2 _direction, LevelSegment _segment)
        {
            return new Vector3(_direction.x * _segment.GetExtents.x * 2f, 0f, _direction.y * _segment.GetExtents.z * 2f);
        }
    }

    [Button]
    public void Clear()
    {
        for (int i = 0; i < currentSegments.Count; i++)
        {
            Destroy(currentSegments[i].gameObject);
        }
        currentSegments.Clear();
    }
}