﻿/*
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.
*/

#if UNITY_EDITOR
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEditor;

namespace Arugula.Math
{
    [CustomEditor(typeof(Dice))]
    public class DiceEditor : Editor
    {

        static Texture2D boxTex;
        class CountedValue
        {
            public int value;
            public int count;

            public CountedValue(int val, int cnt)
            {
                value = val;
                count = cnt;
            }
        }

        Dice dice;
        int output;
        static bool autoRefresh = true;
        static int seed = 0;
        static GUIStyle probabiltyLabelStyle;

        List<CountedValue> outputs = new List<CountedValue>();

        private void OnEnable()
        {
            dice = (Dice)target;
            if (autoRefresh)
            {
                Refresh();
            }
        }

        void Refresh()
        {
            var prevState = Random.state;
            outputs.Clear();
            Random.InitState(12);
            Roll(10000);
            Random.state = prevState;
        }

        void Roll(int qty = 1)
        {
            for (int i = 0; i < qty; i++)
            {
                output = dice.Roll();
                var c = outputs.FirstOrDefault(x => x.value == output);
                if (c == null)
                    outputs.Add(new CountedValue(output, 1));
                else
                    c.count++;
            }

        }

        public override void OnInspectorGUI()
        {
            if (probabiltyLabelStyle == null)
            {
                probabiltyLabelStyle = new GUIStyle(EditorStyles.label);
                probabiltyLabelStyle.alignment = TextAnchor.MiddleLeft;
            }

            bool refresh = false;
            EditorGUI.BeginChangeCheck();
            base.OnInspectorGUI();
            if (EditorGUI.EndChangeCheck())
            {
                refresh = true;
            }
            GUILayout.Space(20);
            EditorGUILayout.LabelField("Preview");
            GUILayout.BeginHorizontal();
            if (GUILayout.Button("Roll (1)")) Roll();
            if (GUILayout.Button("Roll (100)")) Roll(100);
            if (GUILayout.Button("Roll (1000)")) Roll(1000);
            if (GUILayout.Button("Roll (100000)")) Roll(100000);
            if (GUILayout.Button("Roll (1000000)")) Roll(1000000);

            GUILayout.EndHorizontal();

            if (GUILayout.Button("Clear"))
            {
                output = 0;
                outputs.Clear();
            }

            if (refresh)
            {
                Refresh();
            }

            Visualize();
        }

        void Visualize()
        {
            autoRefresh = EditorGUILayout.Toggle("Auto Refresh", autoRefresh);
            EditorGUI.BeginChangeCheck();
            seed = EditorGUILayout.IntField("Seed", seed);
            if (EditorGUI.EndChangeCheck())
                Refresh();

            GUILayout.Label("Samples: " + outputs.Sum(x => x.count));

            if (outputs.Count == 0)
                return;


            var fullWidth = Screen.width;
            var rect = GUILayoutUtility.GetRect(fullWidth, 140);

            var ordered = outputs.OrderBy(x => x.value).ToArray();

            float width = rect.width / ordered.Length;

            var min = outputs.Min(x => x.count);
            var max = outputs.Max(x => x.count);

            for (int i = 0; i < ordered.Length; i++)
            {
                var x = width * i;
                float p = Mathf.InverseLerp(0, max, ordered[i].count);
                var height = 100 * p;
                if (height == 0)
                    height = 1;

                string labelText = ordered[i].value.ToString();
                bool rotate = labelText.Length > 2;
                Rect barRect = new Rect(rect.x + x + 1, rect.y + rect.height - 40, width - 2, -height);
                GUI.DrawTexture(barRect, Texture2D.whiteTexture);
                Rect labelRect = new Rect(rect.x + x + (width / 2) - (rotate ? -10 : 5), rect.y + rect.height - 40, 100, 20);

                if (rotate)
                    GUIUtility.RotateAroundPivot(75, labelRect.position);

                GUI.Label(labelRect, labelText, probabiltyLabelStyle);
                if (rotate)
                    GUIUtility.RotateAroundPivot(-75, labelRect.position);
            }
        }
    }

    [CustomPropertyDrawer(typeof(Dice.WeightedString))]
    [CustomPropertyDrawer(typeof(Dice.WeightedBool))]
    [CustomPropertyDrawer(typeof(Dice.WeightedFloat))]
    [CustomPropertyDrawer(typeof(Dice.WeightedInt))]
    [CustomPropertyDrawer(typeof(Dice.WeightedTransform))]
    [CustomPropertyDrawer(typeof(Dice.WeightedGameObject))]
    [CustomPropertyDrawer(typeof(Dice.WeightedObject))]
    [CustomPropertyDrawer(typeof(Dice.WeightedVector2))]
    [CustomPropertyDrawer(typeof(Dice.WeightedVector3))]
    [CustomPropertyDrawer(typeof(Dice.WeightedQuaternion))]
    [CustomPropertyDrawer(typeof(Dice.WeightedSprite))]
    [CustomPropertyDrawer(typeof(Dice.WeightedMaterial))]
    [CustomPropertyDrawer(typeof(Dice.WeightedMesh))]
    [CustomPropertyDrawer(typeof(Dice.WeightedColor))]
    public class DiceWeightedValueDrawer : PropertyDrawer
    {
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            EditorGUI.BeginProperty(position, label, property);

            var ignore = property.FindPropertyRelative("ignore");
            var value = property.FindPropertyRelative("value");
            var weight = property.FindPropertyRelative("weight");

            var toggleRect = new Rect(position.x + 15, position.y, 20, 20);
            var valueRect = new Rect(position.x + 20, position.y, (position.width) / 2f, position.height);
            var weightRect = new Rect(position.x + 20 + valueRect.width, position.y, -20 + (position.width) / 2f, position.height);

            ignore.boolValue = !GUI.Toggle(toggleRect, !ignore.boolValue, "");
            EditorGUI.PropertyField(valueRect, value, new GUIContent(""));
            EditorGUI.PropertyField(weightRect, weight, new GUIContent(""));

            property.serializedObject.ApplyModifiedProperties();

            EditorGUI.EndProperty();
        }
    }
}
#endif