using System.Collections.Generic;
using System.Linq;
using Sirenix.OdinInspector.Editor;
using UnityEditor;
using UnityEngine;
using VOID.ScriptableObjects.World;

namespace VOID.Editor.ValueDrawers
{
    [DrawerPriority(DrawerPriorityLevel.SuperPriority)]
    public class WorldAreaGeneratorSettingsDrawer : OdinValueDrawer<WorldAreaGeneratorSettings>
    {
        protected override void DrawPropertyLayout(GUIContent label)
        {
            var parent = ValueEntry?.Property?.Parent?.ValueEntry?.WeakSmartValue;
            if (parent is List<WorldAreaGeneratorSettings> list)
            {
                var percent = ValueEntry.SmartValue.weight / list.Sum(group => group.weight);
                var colorProgress = ValueEntry.SmartValue.weight / list.Max(group => group.weight);
                var style = new GUIStyle();
                style.alignment = TextAnchor.MiddleCenter;
                style.fontStyle = FontStyle.Bold;
                style.normal.textColor = Color.white;
                style.normal.background = GetBackgroundColor(Color.Lerp(Color.red, Color.green, colorProgress));

                EditorGUILayout.BeginHorizontal();
                GUILayout.Box($"{Mathf.FloorToInt(percent*100)}%", style, GUILayout.Width(35), GUILayout.ExpandHeight(true));
                EditorGUILayout.BeginVertical();
                CallNextDrawer(label);
                EditorGUILayout.EndVertical();
                EditorGUILayout.EndHorizontal();
            }
            else
            {
                CallNextDrawer(label);
            }
        }
        
        private static Texture2D GetBackgroundColor(Color color)
        {
            var texture = new Texture2D(1, 1);
            texture.SetPixel(0, 0, color);
            texture.Apply();
            return texture;
        }
    }
}