using UnityEngine;
using System.Collections;

public class BallController : MonoBehaviour {

    public float Speed = 5; 
    public float ActiveSpeed = 7;
    public Sprite InactiveSprite;
    public Sprite ActiveSprite;
    public AudioClip StruckClip;

    public bool Active = false;


    private SpriteRenderer rend;
    private Rigidbody2D r2;
    //private Collider2D collider;
    private float lastSoundTime = -999;

    void Start()
    {
        r2 = GetComponent<Rigidbody2D>();
        rend = GetComponent<SpriteRenderer>();
        //collider = GetComponent<Collider2D>();
        RandomStartMove();
	}
	
	// Update is called once per frame
	void Update () {
        rend.sprite = (Active) ? ActiveSprite : InactiveSprite;
	}

    void FixedUpdate()
    {
        if (BoundsHelper.WrapAtBounds(transform))
            Active = false;

        gameObject.layer = LayerMask.NameToLayer((Active) ? "LiveBall" : "DeadBall");

        MaintainSpeed();
    }

    void OnCollisionEnter2D(Collision2D col)
    {
        if(col.gameObject.tag == "Player")
        {
            if (!Active)
            {
                Active = true;
                ClockControl.Punch(0.035f);
            }

            if (Time.time - lastSoundTime > 0.5f)
            {
                if (StruckClip != null)
                    iTween.Stab(gameObject, StruckClip, 0f);
                lastSoundTime = Time.time;
            }

        }

        ZoidSmash smash = col.gameObject.GetComponent<ZoidSmash>();
        if (smash != null)
            smash.Smash(r2.velocity.normalized);
    }

    private void RandomStartMove()
    {
        Vector2 dir = Random.insideUnitCircle.normalized;

        Vector2 accel = (dir * Speed) - r2.velocity;
        Vector2 force = r2.mass * accel / Time.fixedDeltaTime;

        r2.AddForce(force);
    }

    private void MaintainSpeed()
    {
        Vector2 dir = r2.velocity.normalized;
        if (r2.velocity.magnitude == 0)
        {            
            dir = Random.insideUnitCircle.normalized;
            Debug.LogWarning("BallController: Unexpected zero velocity, chose random dir " + dir);
        }

        Vector2 accel = (dir * ((Active) ? ActiveSpeed : Speed)) - r2.velocity;
        Vector2 force = r2.mass * accel / Time.fixedDeltaTime;

        r2.AddForce(force);
    }
}
