using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(WallController))]
public class TracerController : MonoBehaviour {

    // wenn Sie diese Checkbox aktivieren, pausiert der
    // Editor nach jeder Drehung, was zum Debuggen praktisch ist
    public bool pauseOnTurns = false;

    public float baseVelocity = 5F;

    public Rigidbody snakeHead; 
    public Transform pointFront;
    public Transform pointBack;
    public Transform rotateBody;

    private Rigidbody myRigidbody = null;
    private WallController wallController = null;
    private float? rotation = null;
    private Vector3 turnStartPositionBack;
    private Vector3 turnStartPositionFront;
    private float distanceForTurn;

    void Awake() {
        myRigidbody = GetComponent<Rigidbody>();
        wallController = GetComponent<WallController>();
    }

    void Start() {
        myRigidbody.velocity = transform.forward * baseVelocity;
        wallController.TracerTurned();
    }

    void Update() {
        if (rotation == null) {
            CheckForTurn();
        } else {
            HandleTurn();
        }
    }

    private void HandleTurn() {
        float distanceCovered = Vector3.Distance(
            turnStartPositionBack,
            pointBack.transform.position);

        //float currentRotation = rotation.Value * distanceCovered / distanceForTurn;

        float currentRotation = Mathf.Sign(rotation.Value) 
                              * Mathf.Rad2Deg
                              * Mathf.Acos(
                                   (distanceForTurn - distanceCovered) / distanceForTurn
                              );

        rotateBody.localRotation = Quaternion.Euler(0F, currentRotation, 0F);

        if (distanceCovered >= distanceForTurn) {
            rotateBody.localRotation = Quaternion.identity;

            transform.Rotate(0F, rotation.Value, 0F);
            transform.position = turnStartPositionFront;
            myRigidbody.velocity = transform.forward * baseVelocity;

            wallController.TracerTurned();

            rotation = null;
        }
    }


    private void CheckForTurn() {
        if (Input.GetKeyDown(KeyCode.LeftArrow)) {
            rotation = -90F;
        } else if (Input.GetKeyDown(KeyCode.RightArrow)) {
            rotation = 90F;
        }

        if (rotation != null) {
            turnStartPositionBack = pointBack.transform.position;
            turnStartPositionFront = pointFront.transform.position;

            distanceForTurn = Vector3.Distance(
                    turnStartPositionBack,
                    turnStartPositionFront);

            if (pauseOnTurns) {
                Debug.Break(); // Den Editor bei jeder Drehung anhalten
            }
        }
    }

}
