using UnityEngine;

#if UNITY_EDITOR
using UnityEditor;
#endif

namespace pdinklag.CPW.Common
{
    /// <summary>
    /// An object that wrestlers can run into.
    /// </summary>
    public class Runnable : MonoBehaviour
    {
        [Tooltip("How will a wrestler crash into this object?")]
        public RunningCrashType CrashType;

        [Tooltip("The wrestler can crash running in the object's forward (+Z) direction.")]
        public bool CrashAllowForward;

        [Tooltip("The wrestler can crash running in the object's back (-Z) direction.")]
        public bool CrashAllowBack;

        [Tooltip("The wrestler can crash running in the object's right (+X) direction.")]
        public bool CrashAllowRight;

        [Tooltip("The wrestler can crash running in the object's left (-X) direction.")]
        public bool CrashAllowLeft;

        [Tooltip("The damage applied when crashing into this.")]
        public Damage CrashDamage;

#if UNITY_EDITOR
        private static readonly float ARC_RADIUS = 0.5f;
        private static readonly float TEST_DISTANCE = 2.0f;
        private static readonly float CRASH_FOV = 90;

        private Vector3 FindCrashPos(Vector3 dir)
        {
            var refPos = transform.position + TEST_DISTANCE * dir;
            Vector3 crashPos = Vector3.zero;
            float closestSqDist = float.PositiveInfinity;
            foreach (var c in GetComponents<Collider>())
            {
                var p = c.ClosestPoint(refPos);
                var d = (p - refPos).sqrMagnitude;
                if (d < closestSqDist)
                {
                    closestSqDist = d;
                    crashPos = p;
                }
            }
            return crashPos;
        }

        private void DrawCrashPreviewArc(Vector3 dir)
        {
            var pos = FindCrashPos(dir);
            Handles.DrawSolidArc(pos, Vector3.up, dir, CRASH_FOV / 2.0f, ARC_RADIUS);
            Handles.DrawSolidArc(pos, Vector3.down, dir, CRASH_FOV / 2.0f, ARC_RADIUS);
        }

        private void OnDrawGizmosSelected()
        {
            Handles.color = Color.green.WithAlpha(0.25f);
            if (CrashAllowForward) DrawCrashPreviewArc(transform.forward);
            if (CrashAllowBack) DrawCrashPreviewArc(-transform.forward);
            if (CrashAllowRight) DrawCrashPreviewArc(transform.right);
            if (CrashAllowLeft) DrawCrashPreviewArc(-transform.right);
        }
#endif
    }
}
