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

public class StarShipController : MonoBehaviour {

	[SerializeField]private HitObjectController hitController = null; // Set from editor
	private StarShip starShip = new StarShip();
	public List<ResourceController> Drop = new List<ResourceController>();

	public bool IsAlive {get { return starShip.IsAlive;}}

	void Start () {
	}

	void Update () {
		
	}

	public static StarShipController Load (StarShip starShip, Transform parent, Vector3 position, Quaternion rotation, List<ResourceController> drop = null) {
		var shipPrototype = Resources.Load<StarShipController> ("Prefabs/StarShips/" + starShip.HullType.ToString ());
		var starShipController = Instantiate<StarShipController>(shipPrototype, position, rotation, parent);
		starShipController.starShip = starShip;
		starShipController.Drop = drop;
		return starShipController;
	}

	public void Fire(Ray ray, int damage) {
		if (!IsAlive) {
			return;
		}
		if (hitController.IsHit (ray)) {
			starShip.Hit (damage);
			if (starShip.IsAlive) {
				Hit (damage);
			} else {
				Destroy ();
			}
		}
	}

	public void OnStart() {

	}

	public void Hit(int damage) {
		TextEffects.Show (transform.position + (Vector3)Random.insideUnitCircle * 0.2f + Vector3.forward, "-1", Color.red);
	}

	public void Destroy() {
		// show destroy effect
		TextEffects.Show (transform.position + (Vector3)Random.insideUnitCircle + Vector3.forward, "Destroy!", Color.red);
		// Destroy(gameObject, 2);
		DestructionEffectController[] controllers = GetComponentsInChildren<DestructionEffectController> ();
		foreach (var controller in controllers) {
			controller.StartDestruction ();
		}
		if (Drop != null) {
			foreach (var resource in Drop) {
				resource.Drop (transform.position);
			}
		}
	}
}
