using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class PlayerManager : MonoBehaviour
{

    public static int P1life = 5;
    public static int P2life = 5;


    public GameObject p1LifeUI;
    public GameObject p2LifeUI;

    public GameObject Player1;
    public GameObject Player2;

    public GameObject SpawnP1;
    public GameObject SpawnP2;

    public bool p1Damage;
    public bool p2Damage;

    public MicrophoneInput microScript1;
    public MicrophoneInput microScript2;

    public GameObject gm;



    void Start()
    {
       
    }

    void Update()
    {
        FindPlayer();


        if (P1life <= 0 || P2life <= 0)
        {
            SceneManager.LoadScene("MainMenu");
        }

        if (Input.GetKeyDown(KeyCode.F1))
            StartCoroutine(SpawnPlayer(1, 2f));

    }

    public void KillPlayer(int player)
    {
        if (player == 1)
            Destroy(Player1);
        if (player == 2)
            Destroy(Player2);

    }
    public void FindPlayer()
    {
        if (Player1 == null)
            Player1 = GameObject.Find("Player1");
        if (Player2 == null)
            Player2 = GameObject.Find("Player2");
    }

  

    public IEnumerator SpawnPlayer(int player, float delay)
    {
        Debug.Log("Spawning");
        yield return new WaitForSeconds(delay);

        if (player == 1)

            Player1 = Instantiate(Player1, SpawnP1.transform.position, Quaternion.identity) as GameObject;

        if (player == 2)
            Player2 = Instantiate(Player2, SpawnP2.transform.position, Quaternion.identity) as GameObject;

        Debug.Log("Player " + player + " spawned");
        
    }
    public void TakeDamage(GameObject player)
    {
        if (player.tag == "Player1" && p1Damage && microScript1.GetComponent<MicrophoneInput>().GetFundamentalFrequency() > 500f)
        {


            StartCoroutine(gm.GetComponent<PlayerManager>().SpawnPlayer(1, 5f));
            PlayerManager.P1life--;
            p1Damage = false;
            Debug.Log(PlayerManager.P1life);


        }

        if (player.tag == "Player2" && p2Damage && microScript2.GetComponent<MicrophoneInput>().GetFundamentalFrequency() > 500f)
        {


            StartCoroutine(gm.GetComponent<PlayerManager>().SpawnPlayer(2, 2f));
            PlayerManager.P2life--;
            p2Damage = false;
            Debug.Log(PlayerManager.P2life);
        }

    }
}
