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

public class PlayerHealth : MonoBehaviour {

    public static PlayerHealth instance;

    public GameObject wheelF, wheelB, cannon, gearF, gearB;

    public int startHealth = 100;
    public int currentHealth;

    public Slider healthSlider;

    bool isDead;

    public GameObject explosion;

    public GameObject gameOverPanel;

    [SerializeField]
    public Text scoreText, bestScoreText;
 
	void Awake () {
        currentHealth = startHealth;
        MakeInstance();
	}

    void MakeInstance() {
        if (instance == null) {
            instance = this;
        }
    }

	void Update () {
        if (currentHealth >= 100) {
            currentHealth = 100;
        }        
    }

    public void PlayerDamage(int damageAmount) {
        currentHealth -= damageAmount;

        healthSlider.value = currentHealth;

        if (currentHealth <= 0 && !isDead) {
            Dead();
        }

    }

    public void AddLife(int addLife) {
        if (currentHealth == 100) {
            addLife = 0;
            ScoreCount.instance.CountScore(+10);
        } else {
            currentHealth += addLife;
            healthSlider.value = currentHealth;
        }
    }

    void OnTriggerEnter2D(Collider2D collision) {
        if (collision.tag == "Life") {
            AddLife(+10);
            Destroy(collision.gameObject);
        }
    }

    void Dead() {
        isDead = true;
        this.gameObject.GetComponent<SpriteRenderer>().sortingLayerName = "Default";
        wheelF.GetComponent<SpriteRenderer>().sortingLayerName = "Default";
        wheelB.GetComponent<SpriteRenderer>().sortingLayerName = "Default";
        cannon.GetComponent<SpriteRenderer>().sortingLayerName = "Default";
        gearF.GetComponent<SpriteRenderer>().sortingLayerName = "Default";
        gearB.GetComponent<SpriteRenderer>().sortingLayerName = "Default";
        GameObject explode = (GameObject)Instantiate(explosion, transform.position, transform.rotation);
        Destroy(explode, 0.6f);
        StartCoroutine(GameOver());
    }

    IEnumerator GameOver() {
        yield return new WaitForSeconds(1);
        
        Time.timeScale = 0f;
        gameOverPanel.SetActive(true);
        scoreText.text = "Coin Score : " + ScoreCount.instance.countScore;
        bestScoreText.text = "Best Score : " + Score.instance.GetHighScore();
    }
}
