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

public class TileManager : MonoBehaviour
{
    [SerializeField]
    private List<TileData> m_tileList = new List<TileData>();

    [SerializeField]
    private Transform m_camTransform;

    private int m_bendProfile = 0;

    private TileController m_previousTile;
    private TileController m_currentTile;

    public enum TileTypes
    {
        BEND_LEFT = -1,
        STRAIGHT = 0,
        BEND_RIGHT = 1,
    };


    private void Start()
    {
        m_currentTile = FindObjectOfType<TileController>();
    }

    // Update is called once per frame
    void Update()
    {

        /*
        if (m_previousTile != null)
        {
            if (Vector3.Distance(m_previousTile.transform.position, Camera.main.transform.position) > m_exitCullDistance)
            {
                Destroy(m_previousTile);
                m_previousTile = null;
            }
        }
        */

        if(Input.GetKeyDown(KeyCode.Space))
        {
            SpawnRandomTile();
        }
    }

    void SpawnRandomTile()
    {
        var _startBendProfile = m_bendProfile;
        TileData _selectedTile = new TileData();

        do
        {
            _selectedTile = m_tileList[Random.Range(0, m_tileList.Count - 1)];
        }
        while (Mathf.Abs(m_bendProfile + (int)_selectedTile.tileType) >= 2);

        m_bendProfile += (int)_selectedTile.tileType;

        var _newTileObj = Instantiate(_selectedTile.prefab);
        _newTileObj.transform.forward = m_currentTile.exitAnchor.transform.forward;

        var _newTileController = _newTileObj.GetComponent<TileController>();

        Vector3 _offset = m_currentTile.exitAnchor.position - _newTileController.entryAnchor.position;
        _newTileObj.transform.position += _offset;

        m_previousTile = m_currentTile;
        m_currentTile = _newTileController;
        
    }
}
