using System;
using Assets;
using UnityEditor;
using UnityEngine;
using Random = UnityEngine.Random;

namespace Editor
{
    [CustomEditor(typeof (GraphGenerator))]
    public class GraphGeneratorUI : UnityEditor.Editor
    {
        private string _threshold;
        private bool _showInfo = false;
        
        public override void OnInspectorGUI()
        {
            GraphGenerator generator = (GraphGenerator)target;

            _showInfo = EditorGUILayout.Foldout(_showInfo, "Debug info");

            if (_showInfo)
            {
                EditorGUILayout.LabelField($"Stage: ", generator.Stage.ToString());
                EditorGUILayout.LabelField($"Took: ", $"{generator.debug.generationTime:F3}s");
            }
            
            DrawDefaultInspector();

            if (GUILayout.Button("Reset")) {
                generator.Reset();
            }
            
            if (GUILayout.Button("Generate Random"))
            {
                generator.seed = (int)(Random.value * int.MaxValue);
                generator.Reset();
                generator.Generate();
            }

            if (GUILayout.Button("Generate")) {
                generator.Generate();
            }

            if (GUILayout.Button("Step")) {
                generator.Step();
            }

            GUILayout.BeginHorizontal();
            {
                _threshold = GUILayout.TextField(_threshold);

                if (GUILayout.Button("Go")) {
                    try
                    {
                        generator.Rewind(float.Parse(_threshold));
                    }
                    catch
                    {
                        GUILayout.Label("You should pass valid number.");
                    }
                }
            }
            GUILayout.EndHorizontal();
        }

        private void OnSceneGUI()
        {
            GraphGenerator generator = (GraphGenerator)target;

            if (generator.VoronoiGenerator != null)
            {
                var moved = Handles.PositionHandle(generator.transform.position + Vector3.up * (float)generator.VoronoiGenerator.Line.Directrix, Quaternion.identity);
                generator.VoronoiGenerator.Line.Directrix = moved.y;
            }
        }
    }
}