#nullable enable
using UnityEditor;
using UnityEngine;

namespace Test.Util
{
    public static class SerializedUtil
    {
        public static T? GetProperty<T>(Object obj, string propertyPath)
        {
            var serializedObject = new SerializedObject(obj);
            var serializedProperty = serializedObject.FindProperty(propertyPath);

            if (serializedProperty is null)
                throw new UnityException($"Given propertyPath '{propertyPath}' is invalid!");

            var serializedPropertyValue = serializedProperty.boxedValue;

            if (serializedPropertyValue is null)
                return default;
                
            if (serializedPropertyValue is not T value)
                throw new UnityException($"Value of serialized property '{propertyPath}' is not equal to '{nameof(T)}'!");
            
            return value;
        }
        public static T[] GetPropertyArray<T>(Object obj, string propertyPath)
        {

            var serializedObject = new SerializedObject(obj);
            var serializedPropertyArray = serializedObject.FindProperty(propertyPath);
        
            if (serializedPropertyArray is null)
                throw new UnityException($"Given propertyPath '{propertyPath}' is invalid!");
        
            if (!serializedPropertyArray.isArray)
                throw new UnityException($"Given propertyPath '{propertyPath}' does not contain array!");

            var array = new T[serializedPropertyArray.arraySize];
            for (var i = 0; i < serializedPropertyArray.arraySize; i++)
            {
                var value = serializedPropertyArray.GetArrayElementAtIndex(i).objectReferenceValue;
                if (value is not T valueT)
                    throw new UnityException($"At least one of values of serialized property array '{propertyPath}' is not equal to '{nameof(T)}'!");
                array[i] = valueT;
            }
            
            return array;
        }
    }
}