using UnityEngine;
using System.Collections;

public class GroundBlockMovementScript : MonoBehaviour
{
    public Vector2 PlacementOffset;
    public float WidthInUnits;
    public float fMoveSpeed;
    MasterControllerScript mcs;
    public bool bMadeFirstMove;

    public Sprite BombedOutSprite;

	// Use this for initialization
	void Start () 
    {
        mcs = GameObject.Find("MasterController").GetComponent<MasterControllerScript>();
	}

	// Update is called once per frame
	void Update ()
	{
	    Vector3 vPosition = transform.position;
	    vPosition.x -=  mcs.GetGroundMoveSpeed() *Time.fixedDeltaTime;
	    if (!bMadeFirstMove)
	    {
            vPosition.x -= mcs.GetGroundMoveSpeed() * Time.fixedDeltaTime;
	        bMadeFirstMove = true;
	    }
	    if (vPosition.x < (-12.0f - (WidthInUnits  -2.0f) *0.5f))
	    {
            Destroy(gameObject);
	    }

	    transform.position = vPosition;
	}

    void OnTriggerEnter2D(Collider2D coll)
    {
        Projectile p = coll.gameObject.GetComponent<Projectile>();
        if (p != null)
        {
            if (p.ShouldCraterTerrain)
                BombedOut();

            Destroy(p.gameObject);
            return;
        }
    }

    void OnCollisionEnter2D(Collision2D coll)
    {
        Projectile p = coll.gameObject.GetComponent<Projectile>();
        if (p != null)
        {
            if( p.ShouldCraterTerrain )
                BombedOut();

            Destroy(p.gameObject);
            return;
        }
    }

    public void BombedOut()
    {
        SpriteRenderer sr = GetComponent<SpriteRenderer>();

        if (sr.sprite == BombedOutSprite)
            return;

        sr.sprite = BombedOutSprite;

        GameObject explosivo = Instantiate(Resources.Load("MineExplosion")) as GameObject;
        explosivo.transform.position = transform.position;
        explosivo.transform.parent = transform;

        GameObject hurtTrigger = Instantiate(Resources.Load("BombedOutHurtTrigger")) as GameObject;
        Vector3 vHurt = transform.position;
        vHurt.y += 0.25f;
        hurtTrigger.transform.position = vHurt;
        hurtTrigger.transform.parent = transform;

        AlartScript alart = GetComponentInChildren<AlartScript>();
        if (alart != null)
        {
            GameObject sign = alart.gameObject;
            Rigidbody2D rb = sign.GetComponent<Rigidbody2D>();
            rb.isKinematic = false;
            rb.fixedAngle = false;
            rb.AddTorque(Random.value * 900.0f);
            rb.AddForce(Vector2.up * (300.0f + Random.value * 400.0f));
            gameObject.layer = LayerMask.NameToLayer("NoCollide");
            Destroy(gameObject, 4.0f);
        }

        CrushableBuilding cb = GetComponentInChildren<CrushableBuilding>();
        if( cb!= null )
            cb.Died(false);
    }
}
