using System;
using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class GravityBody : MonoBehaviour
{
    public Action<GravityAttractor> OnGravityAttractorChanged;
    public GravityAttractor CurrentPlanet;

    private Rigidbody _rigidbody;

    public object DistanceFromPlanet
    {
        get { return Vector3.Distance(transform.position, CurrentPlanet.transform.position); }
    }

    private void Awake()
    {
        CurrentPlanet = null;
        _rigidbody = GetComponent<Rigidbody>();

        _rigidbody.useGravity = false;
        _rigidbody.constraints = RigidbodyConstraints.FreezeRotation | RigidbodyConstraints.FreezePositionX;
    }

    private void FixedUpdate()
    {
        float currentValue = float.MaxValue;
        GravityAttractor planetToUse = null;
        if (CurrentPlanet != null)
        {
            planetToUse = CurrentPlanet;
            currentValue = Vector3.Distance(transform.position, planetToUse.transform.position) * Mathf.Abs(planetToUse.Gravity / 2);
        }

        var hitInfo = Physics.SphereCastAll(transform.position, 30f, Vector3.one);

        foreach (var hit in hitInfo)
        {
            var planet = hit.transform.GetComponent<GravityAttractor>();
            if (planet != null)
            {
                var thisPlanetValue = Vector3.Distance(transform.position, planet.transform.position) * Mathf.Abs(planet.Gravity / 2);

                if (thisPlanetValue < currentValue)
                {
                    planetToUse = planet;
                    currentValue = thisPlanetValue;
                }
            }
        }

        if (CurrentPlanet != planetToUse)
        {
            CurrentPlanet = planetToUse;
            OnGravityAttractorChanged(planetToUse);
        }
    }
}