using System.Collections;
using UnityEngine;

public class DemonMovement : MonoBehaviour
{

    public float minAngle;
    public float maxAngle;
    public float minRotationSpeed;
    public float maxRotationSpeed;
    public float stopTime;

    private int RotationSign;
    private float SelectedAngle;
    private float SelectedRotationSpeed;
    private float MaxRotationSpeedRate = 1;
    private float CurrentRotationSpeedRate;
    private float RecoveryRotationSpeedRate;

    // Start is called before the first frame update
    void Start()
    {
        CurrentRotationSpeedRate = maxRotationSpeed;
        RecoveryRotationSpeedRate = maxRotationSpeed / 20;

        StartCoroutine(RotateObject());
    }

    public void OverrideRotationSpeed()
    {
        CurrentRotationSpeedRate = Mathf.Max(CurrentRotationSpeedRate - 0.3f, 0.1f);
    }


    IEnumerator RotateObject()
    {
        float deltaAngle = 0;
        Quaternion startRotation;

        while (true)
        {
            SelectedAngle = Random.Range(minAngle, maxAngle);
            RotationSign = randomSign();
            SelectedRotationSpeed = Random.Range(minRotationSpeed, maxRotationSpeed);

            // save starting rotation position
            startRotation = transform.rotation;
            deltaAngle = 0;

            //isRotating = true;

            // rotate until reaching angle
            while (deltaAngle < SelectedAngle)
            {
                deltaAngle += SelectedRotationSpeed * CurrentRotationSpeedRate * Time.deltaTime;
                deltaAngle = Mathf.Min(deltaAngle, SelectedAngle);

                transform.rotation = startRotation * Quaternion.AngleAxis(deltaAngle, Vector3.forward * RotationSign);

                CurrentRotationSpeedRate = Mathf.Min(
                    CurrentRotationSpeedRate + Time.deltaTime * RecoveryRotationSpeedRate,
                    MaxRotationSpeedRate);

                yield return null;
            }

            //isRotating = false;

            yield return new WaitForSeconds(stopTime);
        }
    }

    private int randomSign()
    {
        return (Random.value > 0.5f) ? 1 : -1;
    }

}
