using UnityEngine;
using System.Collections;

public class CrushableBuilding : MonoBehaviour
{

    public int Health;
    private int iRemainingHealth;

    public Sprite CrushedSprite;

    public bool bHandledDead;

    public GameObject CrushedParticle;

	// Use this for initialization
	void Start ()
	{
	    iRemainingHealth = Health;
	    Destroy(gameObject, 12);
	}

    public void Died( bool bWasCrushed )
    {
        if (bHandledDead)
            return;

        bHandledDead = true;
        SpriteRenderer sr = GetComponent<SpriteRenderer>();
        sr.sprite = CrushedSprite;

        BoxCollider2D bc = GetComponent<BoxCollider2D>();
        bc.enabled = false;

        Vector3 vExplosionPos = transform.position;

        if (bWasCrushed)
        {
            vExplosionPos.x -= 1.0f;
            for (int t = 0; t < 4; t++)
            {
                GameObject go = Instantiate(CrushedParticle);
                go.transform.position = vExplosionPos;
                vExplosionPos.x += 0.5f;
                vExplosionPos.y += -0.2f + (0.4f*Random.value);
                go.transform.parent = transform;
                Destroy(go, 2.0f);
            }
        }
        else
        {
            GameObject go = Instantiate(CrushedParticle);
            go.transform.position = vExplosionPos;
            vExplosionPos.x += 0.5f;
            vExplosionPos.y += -0.2f + (0.4f * Random.value);
            go.transform.parent = transform;
            Destroy(go, 2.0f);
            
        }

        MasterControllerScript mcs = GameObject.Find("MasterController").GetComponent<MasterControllerScript>();
        mcs.AddScore(1000 + mcs.iWhatWaveIsIt * 100);

        if (mcs.playerScript != null)
        {
            mcs.playerScript.Speakerbox.PlayOneShot( mcs.playerScript.wavCrushBuilding);
        }
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        Debug.LogWarning("omg touched by layer " + other.gameObject.layer + "and player is " + LayerMask.NameToLayer("PlayerProjectile"));

        if ((other.gameObject.layer == LayerMask.NameToLayer("Player") ||
            other.gameObject.layer == LayerMask.NameToLayer("PlayerProjectile")))
        {
            Debug.LogWarning("Shot or player'd!!");
            Projectile p = other.GetComponent<Projectile>();

        }
    }
}
