using UnityEngine;

public class LevelController : Singleton<LevelController>
{
    public Vector2 Gravity { get; private set; } = Vector2.down;
    public Level CurrentLevel { get; private set; }

    [SerializeField]
    private Level firstLevel;

    [SerializeField]
    private Collider2D[] levelColliders;

    private GameState state;

    private bool respawn = false;

    private void Awake()
    {
        Events.Instance.levelEntered.AddListener(LevelEntered);
        state = ObjectHolder.Instance.gameState;
    }

    private void Start()
    {
        if (!firstLevel)
            Debug.LogError(string.Format("First Level is not set on {0}! Checkpoints might not work!", this));
        else
        {
            CurrentLevel = firstLevel;
            firstLevel.SpawnPlayer(0);

            // freeze player at game begin

            if (state.currentGameState == GameStateEnum.world)
                ObjectHolder.Instance.Player.Freeze();
        }
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.LeftControl) && ObjectHolder.Instance.gameState.currentGameState == GameStateEnum.level)
        {
            ObjectHolder.Instance.Player.Die();
            Respawn();
        }
    }



    private void Respawn()
    {
        CurrentLevel.SpawnPlayer();
    }

    public void SetColliders(bool state)
    {
        if (levelColliders == null)
        {
            Debug.LogError(string.Format("Colliders are not set on {0}!", this));
            return;
        }

        for (int i = 0; i < levelColliders.Length; i++)
            levelColliders[i].enabled = state;
    }

    private void LevelEntered(Level level)
    {
        CurrentLevel = level;
        Gravity = level.Gravity;

        if (Mathf.Abs(Gravity.x) > Mathf.Abs(Gravity.y))
            Gravity = new Vector2(Mathf.Sign(Gravity.x), 0);
        else
            Gravity = new Vector2(0, Mathf.Sign(Gravity.y));

        // mark corresponding level wrapper as player present
        if (level.parentLevelWrapper)
            level.parentLevelWrapper.SetPlayerPresentJustHere();
    }
}