using System.Collections.Generic;
using UnityEngine;

public class Level : MonoBehaviour
{
    public Vector2 Gravity
    {
        get
        {
            return (down.position - up.position).normalized;
        }
    }

    [SerializeField]
    private Transform up;
    [SerializeField]
    private Transform down;
    [SerializeField]
    private List<Checkpoint> checkpoints;

    public int currentCheckpoint = 0;

    private bool isQuitting = false;
    
    [HideInInspector]
    public Wrapper parentLevelWrapper;
    

    public Checkpoint GetCurrentCheckpoint()
    {
        return checkpoints[currentCheckpoint];
    }

    private void CheckpointEntered(Checkpoint cp)
    {
        if(checkpoints.Contains(cp))
            currentCheckpoint = checkpoints.IndexOf(cp);
    }

    public void SpawnPlayer()
    {
        SpawnPlayer(currentCheckpoint);
    }

    public void SpawnPlayer(int index)
    {
        if (checkpoints == null || checkpoints.Count == 0)
            Debug.LogError(string.Format("Checkpoints are not set in {0}!", this));
        else if (index < 0 || index >= checkpoints.Count)
        {
            Debug.LogError(string.Format("Cannot spawn player at {0}th checkpoint! There are {1} of them! Spawning player at 0th checkpoint", index, checkpoints.Count));
            SpawnPlayer(checkpoints[0]);
        }
        else
            SpawnPlayer(checkpoints[index]);
    }

    public void SpawnPlayer(Checkpoint cp)
    {
        ObjectHolder.Instance.Player.Teleport(cp.transform.position);
        Events.Instance.checkpointEntered.Invoke(cp);
        ObjectHolder.Instance.Player.Resurrect();
    }
    
    private void Awake() {
        if (transform.parent)
            parentLevelWrapper = transform.parent.GetComponentInParent<Wrapper>();
    }
    
    private void OnEnable()
    {
        Events.Instance.checkpointEntered.AddListener(CheckpointEntered);
    }

    private void OnDisable()
    {
        if(!isQuitting)
            Events.Instance.checkpointEntered.RemoveListener(CheckpointEntered);
    }

    private void OnApplicationQuit()
    {
        isQuitting = true;
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        Events.Instance.levelEntered.Invoke(this);
    }

    private void Reset()
    {
        if(checkpoints == null)
            transform.GetComponentsInChildren(checkpoints);
    }
}