using UnityEngine;
using UnityEngine.UI;
using XInputDotNetPure;

public class TankHealth : MonoBehaviour
{
    public float m_StartingHealth = 100f;          
    public Slider m_Slider;                        
    public Image m_FillImage;                      
    public Color m_FullHealthColor = Color.green;  
    public Color m_ZeroHealthColor = Color.red;    
    public GameObject m_ExplosionPrefab;

    private GameObject m_ExplosionGameobject;
    public float m_CurrentHealth;  
    public bool m_Dead;            


    private void OnEnable()
    {
        m_CurrentHealth = m_StartingHealth;
        m_Dead = false;

        SetHealthUI();
    }
    

    public void TakeDamage(float amount)
    {
        // Adjust the tank's current health, update the UI based on the new health and check whether or not the tank is dead.
        m_CurrentHealth -= amount;

        //Make the controller of the player taking damage vibrate
        PlayerIndex tankID = (PlayerIndex) gameObject.GetComponent<TankMovement>().m_PlayerNumber -1;
        GamePadManager.Vibrate(tankID, 0.25f, 0.5f);

        SetHealthUI();
        if (m_CurrentHealth <= 0f && !m_Dead)
        {
            OnDeath();
        }
    }


    public void SetHealthUI()
    {
        // Adjust the value and colour of the slider.
        m_FillImage.fillAmount = m_CurrentHealth/m_StartingHealth;

        m_FillImage.color = Color.Lerp(m_ZeroHealthColor, m_FullHealthColor, m_CurrentHealth/m_StartingHealth);
    }


    private void OnDeath()
    {
        // Play the effects for the death of the tank and deactivate it.
        m_Dead = true;

        m_ExplosionGameobject = Instantiate(m_ExplosionPrefab) as GameObject;

        m_ExplosionGameobject.transform.position = transform.position;

        gameObject.SetActive(false);

        //Make the controller of the player taking damage vibrate
        PlayerIndex tankID = (PlayerIndex)gameObject.GetComponent<TankMovement>().m_PlayerNumber - 1;
        GamePadManager.Vibrate(tankID, 1f, 1f);
    }
}