using UnityEngine;
using System.Collections;
using UnityEngine.InputSystem;

public class LevelEnder : MonoBehaviour
{
    public WorldFiller worldFiller;

    public BallSpawner ballSpawner;

    public MultiplierSpawner multiplierSpawner;

    public SharkSpawner sharkSpawner;

    public CakeSpawner cakeSpawner;

    public MusicManager musicManager;

    public Player player;

    public SpriteRenderer levelEndTally;

    public SpriteRenderer levelEndTallyBackground;

    public Animator levelEndTallyAnimator;

    public AudioClip victory;

    private AudioSource audioSource;

    private bool levelEnded = false;

    private bool accelerate = false;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        audioSource = GetComponent<AudioSource>();
    }

    // Update is called once per frame
    void Update()
    {
        // Check for victory condition.
        if (
            player && 
            player.percentCovered >= 80 && 
            !levelEnded
        )
        {
            musicManager.PauseMusic();
            audioSource.PlayOneShot(victory);
            levelEnded = true;
            StartCoroutine(EndLevelAfterDelay());
        }

        if (
            levelEnded && 
            (
                Mouse.current.leftButton.wasPressedThisFrame ||
                Keyboard.current.anyKey.wasPressedThisFrame
            )
        )
        {
            accelerate = true;
        }
    }

    public void EndLevel()
    {
        // Stop all spawners.
        ballSpawner.StopSpawning();
        multiplierSpawner.StopSpawning();
        sharkSpawner.StopSpawning();
        cakeSpawner.StopSpawning();

        // Show the level end tally.
        musicManager.PlayVictoryMusic();
        levelEndTally.enabled = true;
        levelEndTallyBackground.enabled = true;
        levelEndTallyAnimator.ResetTrigger("replay");
        levelEndTallyAnimator.SetTrigger("replay");

        // Destroy all objects other than the player.
        ClearBoard();
    }

    private void ClearBoard()
    {
        // Clear the game board by destroying all objects except the player.
        var yummies = GameObject.FindGameObjectsWithTag("Yummy");
        var multipliers = GameObject.FindGameObjectsWithTag("Multiplier");
        var shark = GameObject.FindGameObjectWithTag("Shark");

        foreach (var yummy in yummies)
        {
            Destroy(yummy);
        }

        foreach (var multiplier in multipliers)
        {
            Destroy(multiplier);
        }

        if (shark != null)
        {
            Destroy(shark);
        }

        worldFiller.ClearSpawnedWalls();
    }

    private IEnumerator EndLevelAfterDelay()
    {
        yield return new WaitForSeconds(victory.length);
        EndLevel();
    }
}
