using System.Collections;
using UnityEngine;

public class DemonHeadMovement : MonoBehaviour
{
    [SerializeField] private GameObject MoveTowardsObject;
    [SerializeField] public GameObject MyDemonParent;
    [SerializeField] private GameObject TargetObject;
    public float minClosingTime = 170;
    public float minInfluanceTime = 90;

    private float distance;
    private float maxSpeed;
    private float currentSpeed;
    private float recoverySpeed;
    private float damageSpeed;
    private float a_parameter;
    private float influance;

    // Start is called before the first frame update
    void Start()
    {
        distance = Vector2.Distance(transform.position, MoveTowardsObject.GetComponent<Transform>().position);

        maxSpeed = distance / minClosingTime;
        currentSpeed = maxSpeed;
        recoverySpeed = maxSpeed / 20;
        damageSpeed = maxSpeed / 10;
        a_parameter = 100 / (minInfluanceTime * minInfluanceTime);

        influance = 100 / minClosingTime;

        StartCoroutine(GettingCloser());

    }

    // Update is called once per frame
    void Update()
    {

    }

    public void OverRideSpeed(float multip)
    {
        currentSpeed = Mathf.Max(currentSpeed - damageSpeed * multip, 0.0f);
    }

    IEnumerator GettingCloser()
    {
        while (true)
        {
            Vector3 newVector = MoveTowardsObject.GetComponent<Transform>().position - transform.position;
            newVector = newVector.normalized;

            transform.position += newVector * Time.deltaTime * currentSpeed;

            currentSpeed = Mathf.Min(
                currentSpeed + Time.deltaTime * recoverySpeed,
                maxSpeed);

            var x = influance * Time.deltaTime * currentSpeed / maxSpeed;
            TargetObject.GetComponent<PlayerLogic>().addToInsanity(x);

            yield return null;
        }
    }

}
