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

public class InGameState : GameState
{
    private GameObject m_PlayerManager;

    const float CONST_Timer = 20.0f;
    private float m_TimeLeft = CONST_Timer;
    private bool m_TimerRunning = false;

    public bool TimerRunning { get { return m_TimerRunning; } }
    public float TimeLeft { get { return m_TimeLeft; } }

    public InGameState()
        :base(GameStateType.Game)
    {
    }

    public override void OnInit()
    {
        base.OnInit();
    }

    public override void OnEnter()
    {
        base.OnEnter();
        // Called on Start
        SceneManager.LoadScene("TestSceneArena");
    }

    public override void OnExit()
    {
        base.OnExit();
    }

    public override void OnUpdate()
    {
        base.OnUpdate();

        if (m_TimeLeft <= 0.0f)
        {
            m_TimeLeft = 0.0f;
            GameManager.Instance.GotoGameOver();
        }

        if (m_TimerRunning)
            m_TimeLeft -= Time.deltaTime;
    }

    public void ResetTimer()
    {
        m_TimeLeft = CONST_Timer;
        m_TimerRunning = true;
    }

    public override void OnSceneLoaded(string _sceneName)
    {
        base.OnSceneLoaded(_sceneName);
        m_PlayerManager = GameObject.FindWithTag("PlayerManager");
        //put round initialisation code here
        SetupGamePlay();

    }

    public void SetDiseasedPlayer(int index, bool isDiseased)
    {
        Player player = m_PlayerManager.GetComponent<PlayerManager>().GetPlayer(index);
        if (player != null)
        { 
            player.GetComponent<PlayerGameplay>().SetIsDiseased(isDiseased);
        }
    }

    public int FindDiseasedPlayerIndex()
    {
        for (int i = 0; i < m_PlayerManager.GetComponent<PlayerManager>().GetPlayerListSize(); i++)
        {
            if ((m_PlayerManager.GetComponent<PlayerManager>().GetPlayer(i).GetComponent<PlayerGameplay>().GetIsDiseased()))
            {
                return i;
            }
        }
        return -1;
    }


    private void SetupGamePlay()
    {
        //Instantiate all required gameplay managers
        //GameObject.Instantiate(Resources.Load<GameObject>("Prefabs/PlayerManager"), Vector3.zero, Quaternion.identity);

        // Randomly determine a diseased player at start for now
        var diseasedPlayerIndex = Random.Range(0, m_PlayerManager.GetComponent<PlayerManager>().NumberOfPlayers - 1);

        SetDiseasedPlayer(diseasedPlayerIndex, true);

        ResetTimer();
    }
}
