using System;
using Sirenix.OdinInspector;
using Sirenix.OdinInspector.Editor;
using Sirenix.OdinInspector.Editor.Validation;
using Sirenix.Utilities;
using UnityEngine;
using VOID.Editor.AttributeValidator.Objects;
using VOID.Generic.Objects.Abstract;

[assembly: RegisterValidator(typeof(AbstractObjectValidator))]

namespace VOID.Editor.AttributeValidator.Objects
{
    public class AbstractObjectValidator : ValueValidator<AbstractObject>
    {
        protected override void Validate(ValidationResult result)
        {
            if (Value == null) return;
            if (OdinPrefabUtility.GetPrefabKind(Value.gameObject) is not PrefabKind.Regular) return;
            
            IsComponentOrderValid(result);
        }

        private void IsComponentOrderValid(ValidationResult result)
        {
            var components = Value.gameObject.GetComponents<Component>();
            var abstractObjectIndex = Array.FindIndex(components, component => component is AbstractObject);

            // *Object is first (or right after Transform)
            if (abstractObjectIndex <= 1) return;

            result.AddError($"{Value.GetType().GetNiceName()} should be first component (right after Transform)")
                .WithFix(() =>
                {
                    for (var i = 0; i < abstractObjectIndex - 1; i++)
                        UnityEditorInternal.ComponentUtility.MoveComponentUp(components[abstractObjectIndex]);
                });
        }
    }
}