using UnityEngine;
using System.Collections;

public class GameManager : MonoBehaviour {
    public GameObject player;
    public GameObject enemy;
    public GameObject boss;
    public GameObject progressBlocker;
    public UnityEngine.UI.Slider healthBar;
    public UnityEngine.UI.Text enemiesLeftUI;
    public GameObject quest1;
    public GameObject questDead;
    public GameObject questBoss;
    public int health = 10;
    public int enemiesLeft = 0;
    public int peopleLeft = 0;
    public GameObject spawnParent;
    public GameObject levelStart;
    public GameObject levelEnd;
    public GameObject cam2d;
    public GameObject cam3d;
    public Opponent[] opponents;
    private bool mode3d = false;
    private int bossBattle = 0;

    void Start() {
        player.transform.position = levelStart.transform.position;
        healthBar.maxValue = health;
        healthBar.value = health;
        healthBar.gameObject.SetActive(false);
    }

    void Update() {
        findOpponents();

        // if all enemies are dead (only player left) let the boss come in
        if (bossBattle == 0 && opponents.Length == 1) {
            bossBattle = 1;
            StartCoroutine(startBoss());
        } else if (bossBattle == 2 && opponents.Length <= 1) {
            Application.LoadLevel("Credits");
        }
    }

    public IEnumerator startBoss() {
        questBoss.SetActive(true);
        yield return new WaitForSeconds(9);
        questBoss.SetActive(false);

        Vector3 pos = new Vector3(Random.Range(levelStart.transform.localPosition.x + 40f, levelEnd.transform.localPosition.x - 5f), 0, -8.85f);
        GameObject go = Instantiate(boss);
        go.transform.parent = spawnParent.transform;
        go.transform.localPosition = pos;

        bossBattle = 2;
    }

    public IEnumerator decreaseHealth(int value) {
        health -= Mathf.Min(value, health);
        healthBar.value = health;
        if (health == 0) {
            questDead.SetActive(true);
            yield return new WaitForSeconds(9);
            Application.LoadLevel(Application.loadedLevel);
        }
    }

    private void findOpponents() {
        opponents = FindObjectsOfType<Opponent>();
        peopleLeft = FindObjectsOfType<Victim>().Length;
        enemiesLeft = opponents.Length;
        enemiesLeftUI.text = enemiesLeft.ToString();
    }

    public IEnumerator enemyDestroyed() {
        if (!mode3d) {
            mode3d = true;
            progressBlocker.SetActive(false);
            quest1.SetActive(true);
            yield return new WaitForSeconds(9);
            quest1.SetActive(false);
            GetComponent<SwitchCamera>().doSwitch = true;
            GetComponent<VictimSpawner>().enabled = true;
        }
    }
}
