using UnityEngine;
using System.Collections.Generic;

public class Missile : BaseObject
{
	public float speed = 4.5f;
	public float explodeRadius = 6.0f;
	public float explodeDamage = 999;
	bool isRising;
	float risingDuration = 4;
	float risingSpeed = 1;
	float fireMark;

	public Vector3 targetPos;

	public ParticleSystem ps;

	public void Init(Vector3 targetPos)
	{
		this.side = -1;
		isRising = true;
		this.targetPos = targetPos;
		this.alive = true;
		fireMark = Time.time;
	}

	void Start()
	{
		Debug.Log("missile start()");
	}

	void Update()
	{
		if (!isServer)
			return;
		if (!alive)
			return;

		if(isRising)
		{
			transform.position += Vector3.up * risingSpeed * Time.smoothDeltaTime;
			if(Time.time - fireMark > risingDuration)
			{
				isRising = false;
			}
		}
		else
		{
			transform.LookAt(targetPos);
			transform.position = Vector3.MoveTowards(transform.position, targetPos, speed * Time.smoothDeltaTime);
		}

		if (Vector3.Distance(transform.position, targetPos) < 1.0f)
		{
			Explode();
		}
	}

	public void Explode()
	{
		if (!alive)
			return;

		List<City> targetCity = Util.GetCitiesInRange(targetPos, 0.5f);

		City firstTarget = (targetCity.Count > 0) ? targetCity[0] : null;

		if (firstTarget != null)
		{
			if (firstTarget.hasMissile)
			{
				Game.GetInstance().CreateBlast(firstTarget.gameObject, targetPos + new Vector3(0, -1, 0), explodeDamage, explodeDamage, false);
			}
			else
			{
				Game.GetInstance().CreateBlast(firstTarget.gameObject, targetPos + new Vector3(0, -1, 0), 0, explodeDamage, true);
			}
		}
		else
		{
			Game.GetInstance().CreateBlast(null, targetPos, 0, 0, true);
		}

		Die();
	}

	public override void Die()
	{
		ps.Stop();
		ps.gameObject.transform.SetParent(null);
		Destroy(ps.gameObject,1.5f);
		base.Die();
	}
}
