using UnityEngine;

namespace Level
{
    public class Level : MonoBehaviour
    {
        public const string ResourcesDirectory = "Levels/";
        public int LevelNumber { get; private set; } = 0;

        public Transform StartingPoint { get; private set; } = null;

        private GameObject prefab = null;
        private GameObject instance = null;
        private bool needsRestart = true;

        public Transform FixedCameraPoint { get; private set; } = null;

        public void SetLevel(int levelNumber)
        {
            LevelNumber = levelNumber;
            prefab = Resources.Load<GameObject>($"{ ResourcesDirectory }{ levelNumber }");
            Disable();
        }

        public void Enable()
        {
            gameObject.SetActive(true);
            needsRestart = true;
        }

        public void Disable()
        {
            if (!needsRestart)
                return;

            if (instance != null)
                Destroy(instance);

            instance = Instantiate(prefab, transform.position, Quaternion.identity, transform);
            StartingPoint = instance.transform.Find("Starting Point");
            FixedCameraPoint = instance.transform.Find("Fixed Camera Point");

            gameObject.SetActive(false);
            needsRestart = false;
        }

        public void EndLevel() => PlayerPrefs.SetInt(LevelNumber.ToString(), 1);

        [ContextMenu("Restart")]
        public void Restart() => LevelManager.Instance.SwitchToLevel(LevelNumber);
    }
}
