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

public class StarShip : MonoBehaviour
{
	public int maxHitPoints = 100;
	public int hitPoints = 100; // healht
	public StarShip enemy;
	public Collider hitCollider = null; // Set from editor
	public List<ShipComponent> components = new List<ShipComponent>();
	public List<Weapon> weapons = new List<Weapon>();
	public GameObject[] weaponRoots = new GameObject[2];

	public void AttachWeapons(Weapon[] newWeapons)
	{
		if (weaponRoots != null && weaponRoots.Length > 0)
		{
			foreach(var root in weaponRoots)
			{
				root.SetActive(false);
			}
			weapons.Clear();
			for(int i = 0; i < weaponRoots.Length && i < newWeapons.Length; i++)
			{
				newWeapons[i].transform.parent = transform;
				newWeapons[i].transform.localPosition = weaponRoots[i].transform.localPosition;
				weapons.Add(newWeapons[i]);
			}
		}
	}

	public void Fire(int weaponNum)
	{ 
		if (weapons != null && weaponNum >= 0 && weaponNum < weapons.Count)
		{
			weapons[weaponNum].Fire();
		}
	}

	public void OnHit(int enemyDamage, Vector3 hitPosition)
	{
		if (hitPoints < 0)
		{
			return;
		}
		hitPoints -= enemyDamage;
		TextEffect.Show(hitPosition, enemyDamage.ToString(), Color.red, Vector3.up);
		BlowEffect.Show (hitPosition);
		if (hitPoints <= 0)
		{
			Die();
		}
	}

	public void OnHit(int enemyDamage)
	{
		OnHit (enemyDamage, transform.position);
	}

	public void Die()
	{
		// aaaaa!
		// Die effect
		StartDestruction ();
	}

	public Vector3 GetRandomHitPoint()
	{
		// TODO
		if (hitCollider != null)
		{
			return hitCollider.bounds.ClosestPoint(transform.position + Random.insideUnitSphere);
		}
		return transform.position + Random.insideUnitSphere;
	}

	public Vector3 GetRandomMissPoint()
	{
		if (Random.Range (0, 100) > 50)
		{
			return transform.position + Random.insideUnitSphere * 0.3f - new Vector3(0, 0.8f, 0);
		}
		return transform.position + Random.insideUnitSphere * 0.3f + new Vector3(0, 0.8f, 0);
	}

	void Start ()
	{
		foreach (var weapon in weapons)
		{
			if (weapon != null)
			{
				weapon.Init(this, enemy);
			}
		}
		RetargetTurrets ();
	}

	void RetargetTurrets()
	{
		TurretController[] turrets = transform.GetComponentsInChildren<TurretController>(true);
		if (turrets != null && enemy != null)
		{
			foreach (var turret in turrets)
			{
				turret.aimObject = enemy.gameObject;
			}
		}

	}
	
	void StartDestruction ()
	{
		PartDestructionController[] parts = gameObject.GetComponentsInChildren<PartDestructionController> ();
		if (parts != null)
		{
			foreach(PartDestructionController part in parts)
			{
				part.StartDestruction();
			}
		}
	}

	void Update () {
	
	}
}
