using System.Collections.Generic;
using UnityEngine;

public class EnemyController : MonoBehaviour {

	public List<GameObject> NextStateParts;
	public int Points;

	public void Start () {
		
	}

	public void Update () {
		if (transform.position.y < LevelManager.Instance.Floor.transform.position.y) {
			Destroy(gameObject);
		}
	}

	public void OnCollisionEnter2D(Collision2D coll) {
		if (coll.gameObject.tag == "Worm" || coll.gameObject.tag == "Projectile") {
			if (coll.transform.position.y > LevelManager.Instance.Floor.transform.position.y + .5f) {
				// The player caught it.
				LevelManager.Instance.AddScore(Points);
				if (NextStateParts == null || NextStateParts.Count == 0) {
					Instantiate(LevelManager.Instance.EnemyDeathPrefab, transform.position, transform.rotation);  // EnemyDeath.
				} else {
					Explode();
				}
			} else {
				// The player lost (enemy hit a low point).
				Instantiate(LevelManager.Instance.ExplosionPrefab, transform.position, transform.rotation);  // Explosion.
				AudioSource.PlayClipAtPoint(LevelManager.Instance.Awa, transform.position);  // Awa sound.
				WormController.Instance.ReplaceToAngryHead();
				GameObject.Destroy(gameObject);  // Remove the enemy GameObject.
				LevelManager.Instance.LoseHeart();  // Lose heart.
				if (NextStateParts != null && NextStateParts.Count > 0) {
					Explode();
				}
			}
		}
		GameObject.Destroy(gameObject);
    }

	private void Explode() {
		for (int i = 0; i < NextStateParts.Count; i++) {
			var part = Instantiate(NextStateParts[i], new Vector2(transform.position.x, transform.position.y + 1), transform.rotation, transform.parent);
			part.GetComponent<Rigidbody2D>().velocity = new Vector2((i + 1) / 2 * (i % 2 == 0 ? -1 : 1), 10);
		}
	}
}
