using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

/// <summary>
/// Figure out ring + square attachment based on distance from center
/// </summary>
public class RingManager : MonoBehaviour
{
    //smallest ring first
    [System.Serializable]
    public class RingWithRadius
    {
        public Rotater ring;
        [HideInInspector]
        public float radius;
    }
    public List<RingWithRadius> rings;

    protected void Start()
    {
        foreach(var ring in rings)
        {
            //dynamically get the radius from the mesh renderers
            Vector3 extents = ring.ring.renderer.bounds.extents;
            ring.radius = extents.x;
        }
    }

    protected float GetDistanceFromCenter(Vector3 pos)
    {
        return (transform.position - pos).magnitude;
    }

    protected Vector3 GetPositionAtRadius(Vector3 pos, float radius)
    {
        Vector3 directionFromCenter = (pos - transform.position).normalized;
        return transform.position + directionFromCenter * radius;
    }

    protected RingWithRadius GetNearestRing(Transform t)
    {
        //Get the nearest ring and radius
        RingWithRadius nearestRing;
        float dist = GetDistanceFromCenter(t.position);
        float errorDist = 1.2f;
        
        if (dist <= rings[0].radius*errorDist)
        {
            nearestRing = rings[0];
        }
        else if (dist <= rings[1].radius * errorDist)
        {
            nearestRing = rings[1];
        }
        else
        {
            nearestRing = rings[2];
        }
        return nearestRing;
    }

    //Which ring should the block at pos attach to?
    public Direction AttachObjectToNearestRing(Transform t)
    {
        RingWithRadius nearestRing = GetNearestRing(t);

        //Attach the object to that ring
//        t.position = GetPositionAtRadius(t.position, nearestRing.radius);
        t.position = GetPositionAtRadius(t.position, nearestRing.radius);
        t.parent = nearestRing.ring.transform;

        return nearestRing.ring.direction;
    }
}
