using UnityEngine;
using System.Collections;

public class ZoidMovementController : MonoBehaviour {

    public float Speed = 5;
    public float MinSpeed = 2;
    public bool InitialTorque = true;
    public float BoundsExtraSpace = 0f;
    public bool StartTowardCenter = false;

    private Rigidbody2D r2;

	void Start () {
        r2 = GetComponent<Rigidbody2D>();
        RandomStartMove();
	}
	
	void FixedUpdate () {
        BoundsHelper.WrapAtBounds(transform, BoundsExtraSpace);
        MaintainSpeed();
	}

    private void RandomStartMove()
    {
        if (InitialTorque)
            r2.AddTorque(Random.Range(-10f, 10f) * r2.mass);

        Vector2 dir = Random.insideUnitCircle.normalized;
        // take the sign of dir that is away from the center, so we don't insta-slam player in opening moment of game
        bool isTowardCenter = (transform.position + (Vector3)dir).magnitude < (transform.position - (Vector3)dir).magnitude;
        if (isTowardCenter != StartTowardCenter)
            dir *= -1;

        Vector2 accel = (dir * Random.Range(MinSpeed, 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("ZoidMovementController: Unexpected zero velocity, chose random dir " + dir);
        }

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

        r2.AddForce(force);
    }
}
