using UnityEngine;
using System.Collections;

public class VictimSpawner : MonoBehaviour {
    public GameObject victim;
    public GameObject spawnParent;
    public GameObject questObject;
    public float range = 5f;
    public float delay = 5f;
    private GameManager gameManager;
    private float nextSpawn = 0f;
    private bool questShown = false;

    void Start() {
        gameManager = FindObjectOfType<GameManager>();
        nextSpawn = Time.time + 10f;
    }

    void Update() {
        if (Time.time > nextSpawn) {
            Vector3 pos = new Vector3(gameManager.player.transform.localPosition.x - 4f, 0, -8.85f);
            bool found = false;

            // don't spawn too many in same area
            foreach (Victim victim in FindObjectsOfType<Victim>()) {
                if (victim.transform.localPosition.x > pos.x - range && victim.transform.localPosition.x < pos.x + range) {
                    found = true;
                    break;
                }
            }

            if (!found) {
                GameObject go = Instantiate(victim);
                go.transform.parent = spawnParent.transform;
                go.transform.localPosition = pos;
                if (!questShown) {
                    StartCoroutine(showQuest());
                }
            }

            nextSpawn = Time.time + delay;
        }
    }

    public IEnumerator showQuest() {
        questShown = true;
        questObject.SetActive(true);
        yield return new WaitForSeconds(8);
        questObject.SetActive(false);
    }
}
