using UnityEditor;
using UnityEngine;

public class FixTMPColor : EditorWindow
{
    private Color originalColor = new Color(0.667f, 0.667f, 0.667f);
    private Color originalColorOutput = new Color(0.667f, 0.667f, 0.667f);
    private Color fixedColor = GetFixedTMPColor(new Color(0.667f, 0.667f, 0.667f));
    private Color fixedColorOutput = GetFixedTMPColor(new Color(0.667f, 0.667f, 0.667f));

    [MenuItem("Tools/Fix TMP Color")]
    public static void ShowWindow()
    {
        GetWindow<FixTMPColor>("Fix TMP Color");
    }

    private void OnGUI()
    {
        EditorGUI.HelpBox(GUILayoutUtility.GetRect(50, 50), "Translates between an intended color and a color value which displays as the intended color when used in the TextMeshPro Vertex Color field.", MessageType.Info);
        
        EditorGUILayout.Space();

        originalColor = EditorGUILayout.ColorField("Original Color", originalColor);
        EditorGUI.DrawRect(GUILayoutUtility.GetRect(50, 50), originalColor);

        EditorGUILayout.Space();
        
        fixedColor = EditorGUILayout.ColorField("Fixed TMP Vertex Color", fixedColor);
        EditorGUI.DrawRect(GUILayoutUtility.GetRect(50, 50), fixedColor);

        if (GUI.changed)
        {
            if (fixedColorOutput != fixedColor)
            {
                originalColor = GetOriginalTMPColor(fixedColor);
            } 
            else if (originalColorOutput != originalColor)
            {
                fixedColor = GetFixedTMPColor(originalColor);
            }
            originalColorOutput = originalColor;
            fixedColorOutput = fixedColor;
        }
    }

    private static Color GetFixedTMPColor(Color input)
    {
        return new Color(
            Mathf.Pow(input.r, 1 / 0.4545f),
            Mathf.Pow(input.g, 1 / 0.4545f),
            Mathf.Pow(input.b, 1 / 0.4545f),
            input.a // Not sure what to do with the alpha channel, leaving it unchanged
        );
    }

    private static Color GetOriginalTMPColor(Color input)
    {
        return new Color(
            Mathf.Pow(input.r, 0.4545f),
            Mathf.Pow(input.g, 0.4545f),
            Mathf.Pow(input.b, 0.4545f),
            input.a // Not sure what to do with the alpha channel, leaving it unchanged
        );
    }
}