using System.Collections.Generic;
using UnityEngine;

public class Wind : MonoBehaviour
{
    public AnimationCurve forceOverDistance;
    public float maxLength = 8;
    public float force = 100;
    public Transform center;
    public float centerRadius = 0;
    public float centerSmooth = 10;

    private void FixedUpdate()
    {
        if (Physics.Raycast(transform.position, transform.forward, out var hit, maxLength))
        {
            if (hit.rigidbody != null)
                hit.rigidbody.AddForce(transform.forward * force * forceOverDistance.Evaluate(hit.distance / maxLength) * Time.fixedDeltaTime);
        }

        // var cols = Physics.OverlapBox(box.transform.position, box.size / 2f, box.transform.rotation);
        // var distanceCol = new Dictionary<Collider, float>();
        // float minDist = 10000000;
        // foreach (var col in cols)
        // {
        //     if (col.attachedRigidbody != null)
        //     {
        //         var distance = (transform.position - col.attachedRigidbody.position).magnitude;
        //         if (distance < minDist)
        //             minDist = distance;

        //         distanceCol[col] = distance;
        //     }
        // }

        // foreach (var pair in distanceCol)
        // {
        //     if (Mathf.Abs(pair.Value - minDist) < distanceMargin)
        //     {
        //         pair.Key.attachedRigidbody.AddForce(transform.forward * force * forceOverDistance.Evaluate(pair.Value) * Time.fixedDeltaTime);
        //     }
        // }
    }

    private void Update()
    {
        if (center != null && centerRadius > 0 && force < 0)
        {
            var cols = Physics.OverlapSphere(center.position, centerRadius);
            foreach (var col in cols)
            {
                if (col.attachedRigidbody != null && !col.attachedRigidbody.isKinematic && col.attachedRigidbody.GetComponent<WindGrabbable>() != null)
                {
                    col.attachedRigidbody.velocity = Vector3.zero;
                    col.attachedRigidbody.position = Vector3.Lerp(col.attachedRigidbody.position, center.position, centerSmooth * Time.deltaTime);
                }
            }
        }
    }

    private void OnDrawGizmos()
    {
        Gizmos.color = Color.yellow;
        var length = maxLength;
        if (Physics.Raycast(transform.position, transform.forward, out var hit, maxLength))
        {
            length = hit.distance;
        }
        Gizmos.DrawLine(transform.position, transform.position + transform.forward * length);

        if (center != null)
            Gizmos.DrawWireSphere(center.position, centerRadius);
    }
}