using System;
using UnityEditor;
using UnityEngine;

namespace Assets.Source.Editor
{
    public class TimeScaleWindow : EditorWindow
    {
        float MAX = 10;
        float[] ITEMS = { 0, 1, 2, 5, 10 };

        static TimeScaleWindow window;
        [MenuItem("Tools/TimeScale")]
        public static void ShowWindow()
        {
            window = GetWindow<TimeScaleWindow>(utility: true, title: "TimeScale");
            window.minSize = new Vector2(10f, 20f);
        }
        void OnGUI()
        {
            GUILayout.BeginHorizontal();
            Scale = (float)Math.Round(Mathf.Pow(GUILayout.HorizontalSlider(Mathf.Sqrt(Scale), 0, Mathf.Sqrt(MAX)), 2), Scale > 1 ? 0 : 1);
            Rect sliderRect = GUILayoutUtility.GetLastRect();
            Scale = EditorGUILayout.FloatField(Scale, GUILayout.MaxWidth(30f));
            GUILayout.EndHorizontal();

            EditorGUI.DrawRect(new Rect(sliderRect.x + 4 + (sliderRect.width - 8) / Mathf.Sqrt(MAX), sliderRect.y, 2f, sliderRect.height), new Color(0, 0, 0, 0.2f));

            #region Context Menu

            Event e = Event.current;
            if (e.type == EventType.ContextClick)
            {
                GenericMenu menu = new GenericMenu();
                for (int i = 0; i < ITEMS.Length; i++)
                {
                    int s = i;
                    menu.AddItem(new GUIContent(ITEMS[s].ToString()), Scale == ITEMS[s], () => { Scale = ITEMS[s]; });
                }
                menu.ShowAsContext();
                e.Use();
            }

            #endregion

        }
        float Scale
        {
            set
            {
                Time.timeScale = value;
            }
            get
            {
                return Time.timeScale;
            }
        }
        private void OnDestroy()
        {
            if (Scale != 1)
                Scale = 1;
        }
    }
}
