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

public class LifeManager : MonoBehaviour {
	public float initialTime= 60f;
    public GameObject _heartsHolder;
    public GameObject _gameover;
	public Text _timeText;
    public float _secondPlayerSpawnOffset;
    public float _deathWait;
    int _numberOfLifes;
    public  Transform[] _playerArr;
    [SerializeField]
    Transform _lastCheckpoint;
	bool isGameOver = false;
	// Use this for initialization
	void Start () {
        _numberOfLifes = _heartsHolder.transform.childCount;
        GetComponent<Menu>().main.sendNavigationEvents = false;
		_timeText.text = initialTime.ToString ();
    }
	void Update(){
		if (!isGameOver) {
			float remainingTime = initialTime - Time.timeSinceLevelLoad;
			int remaininIntTime = (int)remainingTime;
			if (remainingTime > 0)
				_timeText.text = remaininIntTime.ToString ();
			else {
				_numberOfLifes = 0;
				 isGameOver=true;
				_playerArr [0].gameObject.GetComponent<PlayerRaycasts> ().DieBoth ();
			}
		}
	}
    public void LoseALife() {
        StartCoroutine(LoseLife());
    }
    IEnumerator LoseLife() {
        yield return new WaitForSeconds(_deathWait);
        _numberOfLifes--;
        if (_numberOfLifes > 0)
        {
            _heartsHolder.transform.GetChild(_numberOfLifes).GetComponent<Image>().color = Color.black;
            GoToLastCheckpoint();
            RestartPlayersPhysics();
        }
        else {
            _gameover.SetActive(true);
            GetComponent<Menu>().main.sendNavigationEvents = true;

        }
    }
    void RestartPlayersPhysics() {
        foreach (Transform player in _playerArr) {
            player.gameObject.GetComponent<PlayerRaycasts>().RestartPhysics();
        }
    }
    void GoToLastCheckpoint()
    {
        _playerArr[0].transform.position = _lastCheckpoint.position;
        _playerArr[1].transform.position = new Vector2(_lastCheckpoint.position.x, _lastCheckpoint.position.y + _secondPlayerSpawnOffset);
        foreach (Transform player in _playerArr) {
            player.GetChild(0).gameObject.SetActive(false);
        }
    }
    public void SetLastCheckpoint(Transform checkpoint) {
        _lastCheckpoint = checkpoint;

    }
}
