using UnityEngine;
using System.Collections;

public class BreakableTreasureHex : MonoBehaviour 
{
    public float MaxHealth;
    float fRemainingHealth;

    public GameObject Debris_OnExplode;
    public Vector2 MinMax_NumShrapnels;

    TM_CombatComponent myCC;
    private bool bDead = false;
    public TreasureLocationComponent myTLC;

    void Awake()
    {
        myCC = GetComponent<TM_CombatComponent>();
    }

	// Use this for initialization
	void Start ()
    {
        myCC.AddOnHitFunction(OnHitByProjectile);
        fRemainingHealth = MaxHealth;
	}
	
	// Update is called once per frame
	void Update ()
    {
	
	}

    public bool OnHitByProjectile( TM_Projectile p)
    {
        if (p.iFakeAltitude != 0)
            return false;

        fRemainingHealth -= p.fDamage;
        if( fRemainingHealth <= 0.0f)
            OnKilled();
        return true;
    }


    public void OnKilled()
    {
        if (bDead)
            return;

        bDead = true;
        if (Debris_OnExplode != null)
        {
            int iNumShrapnels = Random.Range((int)MinMax_NumShrapnels.x, (int)MinMax_NumShrapnels.y + 1);
            for (int t = 0; t < iNumShrapnels; t++)
            {
                GameObject go = Instantiate(Debris_OnExplode);
                go.transform.position = transform.position;
                DebrisComponent dc = go.GetComponent<DebrisComponent>();
                dc.Launch();
            }
        }

        GameManager theGame = GameObject.Find("GameManager").GetComponent<GameManager>();
        theGame.SpawnCollectablesFromTreasureHex(transform.position);

        myTLC.ReportBrokenHex();

        Destroy(gameObject);
    }
}


/*
    //Hex placement science:
 *  // horizontal hexes go + 1.5x
 *  // shift to next row with 
 *  // 0.75x and -1.25y


*/