using System;
using UnityEngine;
using System.Collections;
using Random = UnityEngine.Random;

public class CageScript : EnemyFloating
{
    public bool FloatingCage;
    public bool BoundToEnemy;

    public GameObject CageShrapnel;

    public GameObject AllyTrappedInMe;

	// Use this for initialization
    protected override void Start()
    {
        base.Start();

        if (FloatingCage)
        {
            float fYDelta = Random.value*-4.0f;
            Vector3 vFootPos = collisionFeet[0].transform.position;
            vFootPos.y += fYDelta;
            collisionFeet[0].transform.position = vFootPos;
            
        }

        if (AllyTrappedInMe != null)
        {
            AllyController ac = AllyTrappedInMe.GetComponent<AllyController>();
            if (ac != null)
                ac.CurrentState = AllyController.AllyState.caged;
        }

        mcs.ActiveCages++;
    }

    public override void Died()
    {
        for (int t = 0; t < 9; t++)
        {
            GameObject trash = Instantiate(CageShrapnel);
            trash.transform.position = transform.position;
            Rigidbody2D r = trash.GetComponent<Rigidbody2D>();
            r.AddForce(Random.insideUnitCircle * (Random.value * 700.0f + 800.0f));
            r.AddTorque(Random.value * 1000.0f - 500.0f);
            Destroy(trash,3.0f);
        }

        if (AllyTrappedInMe != null)
        {
            AllyTrappedInMe.transform.parent = null;
            AllyController ac = AllyTrappedInMe.GetComponent<AllyController>();
            if (ac != null)
                ac.CurrentState = AllyController.AllyState.heading_to_player;
        }

        mcs.ActiveCages--;
        Destroy(gameObject);
    }

    public override void UpdateMotion()
    {
        if (BoundToEnemy)
            return;

        if (!FloatingCage)
            bShouldBoost = false;

        base.UpdateMotion();

        if (transform.position.x < -8.0f)
        {
            mcs.ActiveCages--;
            Destroy(gameObject);
        }
    }

    public override void OnCollisionEnter2D(Collision2D other)
    {
        //if we're a static obstacle, and hit the player, damage the player
        PlayerController pc = other.gameObject.GetComponent<PlayerController>();
        if (pc != null)
        {
            //if we're jumped on, be crushed!
            Rigidbody2D r = pc.GetComponent<Rigidbody2D>();
            if( r.transform.position.y > transform.position.y )
                Died();

        }
    }
}
