using GatherAndDefend.Events;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class VictoryDefeat : MonoBehaviour
{
    public const float positionLoseLimit = -10.0f;

    [SerializeField] private Animator _victoryAnimator;
    [SerializeField] private Animator _defeatAnimator;

    private bool _lastWaveCompleted = false;
    private bool _isShowingVictoryOrDefeat = false;
    
    private WorldMapSave _wms;

    private void Start()
    {
        _wms = new WorldMapSave();
        _isShowingVictoryOrDefeat = false;

        EventAggregator.Instance.GetEvent<LastWaveCompletedEvent>().Attach(HandleLastWaveCompletedEvent);
    }

    private void OnDestroy()
    {
        EventAggregator.Instance.GetEvent<LastWaveCompletedEvent>().Detach(HandleLastWaveCompletedEvent);
    }

    private void HandleLastWaveCompletedEvent() 
    {
        _lastWaveCompleted = true;
    }

    private void Update()
    {
        if (_isShowingVictoryOrDefeat) return;

        List<LevelObject> opponentsList = LevelManager.Instance.GetAll<LevelObject>(x => x is Opponent);

        // Win if the waves are finished and there are no more monsters.
        if(_lastWaveCompleted && opponentsList.Count == 0) 
        {
            _victoryAnimator.Play("ShowVictoryOrDefeat");
            _isShowingVictoryOrDefeat = true;
            // win !
            _wms.UnlockNextLevel();
        }
        
        // Lose if one of the enemies arrives behind our line of defense.
        foreach (Opponent opponent in opponentsList)
        {
            if (opponent == null) return;
            if (opponent.transform.position.x < positionLoseLimit)
            {
                _defeatAnimator.Play("ShowVictoryOrDefeat");
                _isShowingVictoryOrDefeat = true;
                // lose :(
            }
        }
    }

}
