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

public class HumanManager : MonoBehaviour
{
    [SerializeField]
    int p_myNumberOfHumansMax;
    static GameObject p_myEarth;
    static GameObject p_myCanvas;

    static Text p_myText;

    static Material p_myMaterial;

    static int p_myNumberOfHumans;
    static int p_myMax;

    static bool p_myInfinity;

    static bool started;

    public static void setInfinity(bool value)
    {
        p_myInfinity = value;
    }
    public static bool getInfinity()
    {
        return p_myInfinity;
    }

    void Awake()
    {
        p_myCanvas = GameObject.FindGameObjectWithTag("Canvas");
        p_myEarth = GameObject.FindGameObjectWithTag("Earth");
        p_myNumberOfHumans = 0;
        p_myMax = p_myNumberOfHumansMax;
        p_myMaterial = GameObject.FindGameObjectWithTag("Earth").transform.GetChild(0).GetComponent<Renderer>().material;
    }

    public static void addHuman()
    {
        Ratio();
    }

    public static void removeHuman()
    {
        Ratio();
    }

    public static void Ratio()
    {
        p_myNumberOfHumans = p_myEarth.GetComponentsInChildren<HumanScript>().Length;
        if (p_myNumberOfHumans > 1)
        {
            started = true;
        }
        if (p_myNumberOfHumans == 1)
        {
            if (started)
            {
                p_myNumberOfHumans = 0;
            }
        }
        if (p_myText == null)
        {
            p_myText = GameObject.FindGameObjectWithTag("Population").GetComponent<Text>();
        }
        else
        {
            if (p_myNumberOfHumans < 2)
            {
                p_myText.text = "Population : " + p_myNumberOfHumans + " human";
            }
            else
            {
                p_myText.text = "Population : " + p_myNumberOfHumans + " humans";
            }
        }
        float ratio = (float)p_myNumberOfHumans / (float)p_myMax;
        p_myMaterial.color = Color.Lerp(Color.white, Color.black, ratio);
        if (!p_myInfinity)
        {
            if (p_myNumberOfHumans == 0)
            {
                Time.timeScale = 0;
                p_myCanvas.GetComponent<CanvasScript>().End("You win");
            }
        }
        if (p_myNumberOfHumans >= p_myMax)
        {
            Time.timeScale = 0;
            p_myCanvas.GetComponent<CanvasScript>().End("You lose");
        }
    }
}
