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

public class CreatureDestroyer : MonoBehaviour {
    public AudioClip explosionSound;
    public GameObject explosion;
    public GameObject pointText;
    public int explosionCount;
    public float explisionDelay;
    public float explosionXDither;
    public float explosionYDither;

	// Use this for initialization
	void Start ()
    { 
        GameObject text = Instantiate<GameObject>(pointText, GetPlacePosition(), Quaternion.identity);
        Progress.Defeat defeat = Progress.LatestDefeat();
        int points = defeat != null ? defeat.Points : 666;
        text.GetComponent<FloatingPointDisplayer>().SetPoints(points);

        StartCoroutine(PlaceExplosions());
	}
	
    IEnumerator PlaceExplosions()
    {
        for (int i = 0; i < explosionCount; i++)
        {
            Vector3 offset = new Vector3(Random.Range(-explosionXDither, explosionXDither), i * explosionYDither);
            GameObject g = Instantiate<GameObject>(explosion, GetPlacePosition() + offset, Quaternion.identity);
            GetComponent<AudioSource>().PlayOneShot(explosionSound);
            print("Placed an explosion");
            Destroy(g, 1f);
            // play a fucking explosion sound
            if (i < explosionCount-1)
            {
                yield return new WaitForSeconds(explisionDelay);
            }
        }
        // kill this mother fucker;
        yield return new WaitForSeconds(1f); // wait for the last explosion to finish
        CameraController.Instance.ReportPhaseCompleted(CameraController.Phase.EXPLODE);
        Destroy(gameObject);
    }

    Vector3 GetPlacePosition()
    {
        return transform.position - new Vector3(0, 2, 0);
    }
}
