using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(WallController))]
public class TracerControllerV1 : TracerControllerBase {

    private float? rotation = null;
    private Vector3 turnStartPositionBack;
    private Vector3 turnStartPositionFront;
    private float distanceForTurn;

    void Awake() {
        InitComponents();
    }

    void Start() {
        StartMoving();
    }

    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() {
        base.CheckForTurn(ref rotation);

        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
            }
        }
    }

}
