using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EndScript : MonoBehaviour
{

    public PlayerScript2[] entereds;

    public bool finished;
    public float finishedat;

    bool appeared;

    public AudioClip myendclip;
    public AudioClip myappearclip;

    private void Awake()
    {
        GetComponent<SpriteRenderer>().enabled = false;
        entereds = new PlayerScript2[] { null, null };
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        PlayerScript2 script = collision.gameObject.GetComponent<PlayerScript2>();
        if (script != null)
        {
            entereds[script.playernumber] = script;
        }
    }

    public void FixedUpdate()
    {
        bool collectablesleft = GameObject.FindGameObjectsWithTag("Collectable").Length > 0;

        if (!appeared && !collectablesleft)
        {
            GetComponent<SpriteRenderer>().enabled = true;
            GetComponent<Animator>().SetTrigger("open");
            appeared = true;
            GetComponent<AudioSource>().PlayOneShot(myappearclip);
            Camera.main.GetComponent<AudioController>().FadeOut(true);
        }
        
        if (entereds[0] != null && entereds[1] != null && !collectablesleft && !finished)
        {
            foreach (PlayerScript2 script in entereds)
            {
                script.LevelEnded();
            }

            finished = true;
            finishedat = Time.time;

            GetComponent<AudioSource>().PlayOneShot(myendclip);
        }
    }

    public void OnGUI()
    {
        //if (finished)
        //    GUI.Label(new Rect(50, 50, 100, 100), "you did id");
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        PlayerScript2 script = collision.gameObject.GetComponent<PlayerScript2>();
        if (script != null)
        {
            entereds[script.playernumber] = null;
        }
    }
}
