﻿/*
MIT License

Copyright(c) 2019 Mitchel Thompson
www.angryarugula.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Arugula.Math;

#if UNITY_EDITOR
using UnityEditor;
#endif

namespace Arugula.Widgets
{
    public class Ruler : MonoBehaviour
    {

        [System.Serializable]
        public class Mark
        {
            public string name;
            public float value;
            public Unit units;
        }

        public Unit units = Unit.Meters;
        [Range(0, 5)]
        public int significantDigits = 2;
        public Transform target;
        public Vector3 targetPosition;
        public bool alwaysDraw = true;
        public bool showCardinalLines = false;
        public Color color = Color.white;

        public List<Mark> marks = new List<Mark>();

        public float Distance
        {
            get
            {
                float distance = DistanceInMeters;
                try
                {
                    distance = distance.ConvertUnits(Unit.Meters, units);
                }
                catch
                {
                    Debug.LogWarning("Reverted Ruler units to " + Unit.Meters);
                    units = Unit.Meters;
                }

                return distance;
            }
        }

        public float DistanceInMeters
        {
            get
            {
                return Vector3.Distance(transform.position, position);
            }
        }

        public override string ToString()
        {
            return Distance.ToString(units);
        }

        public Vector3 position
        {
            get
            {
                if (target == null)
                    return targetPosition;
                else
                    return target.position;
            }
        }
#if UNITY_EDITOR
        private void OnDrawGizmos()
        {
            if (alwaysDraw)
                Draw();
        }

        private void OnDrawGizmosSelected()
        {
            if (!alwaysDraw)
                Draw();
        }

        void Draw()
        {
            DrawDimension(transform.position, position, color);

            if (showCardinalLines)
            {
                Vector3 a = transform.position;
                a.z = position.z;
                DrawDimension(transform.position, a, color * 0.5f, false);

                Vector3 b = a;
                b.x = position.x;
                DrawDimension(a, b, color * 0.5f, false);

                DrawDimension(b, position, color * 0.5f, false);
            }

            foreach (var m in marks)
                DrawMark(m);
        }

        void DrawMark(Mark m)
        {
            Vector3 dir = position - transform.position;
            dir.Normalize();

            float meters = 0;
            try
            {

                meters = m.value.ConvertUnits(m.units, Unit.Meters);
            }
            catch
            {
                Debug.LogWarning($"Reverting Mark {m.name} to meters.");
                m.units = Unit.Meters;
            }

            //TODO: something smarter
            //Vector3 tickDir = SceneView.currentDrawingSceneView.camera.transform.up;
            Vector3 tickDir = Vector3.up;

            Vector3 pos = transform.position + dir * meters;
            Vector3 tickStart = pos + tickDir * HandleUtility.GetHandleSize(pos) * 0.2f;
            Vector3 tickEnd = pos - tickDir * HandleUtility.GetHandleSize(pos) * 0.2f;
            Handles.color = Color.red;
            Handles.DrawLine(tickStart, tickEnd);
            string dStr = $"f{significantDigits}";
            Handles.Label(tickEnd, $"{m.name}\r\n{m.value.ToString(m.units, dStr)}");
        }

        void DrawDimension(Vector3 a, Vector3 b, Color color, bool dashed = true)
        {
            float distance = Vector3.Distance(a, b);
            try
            {
                distance = distance.ConvertUnits(Unit.Meters, units);
            }
            catch
            {
                Debug.LogWarning("Reverted Ruler units to " + Unit.Meters);
                units = Unit.Meters;
            }

            //TODO: something smarter
            //Vector3 tickDir = SceneView.currentDrawingSceneView.camera.transform.up;
            Vector3 tickDir = Vector3.up;
            Handles.color = color;
            if (dashed)
                Handles.DrawDottedLine(a, b, 5f);
            else
                Handles.DrawLine(a, b);

            Handles.Label(Vector3.Lerp(a, b, 0.5f), distance.ToString(units, $"f{significantDigits}"));
            Handles.DrawLine(a + tickDir * HandleUtility.GetHandleSize(a) * 0.1f, a - tickDir * HandleUtility.GetHandleSize(a) * 0.1f);
            Handles.DrawLine(b + tickDir * HandleUtility.GetHandleSize(b) * 0.1f, b - tickDir * HandleUtility.GetHandleSize(b) * 0.1f);
        }
#endif
    }
}