using UnityEngine;
using UnityEditor;

public abstract class BaseRetargetingEditor : Editor
{
    protected bool isDirty = false;
    protected double lastUpdateTime;
    protected const double UPDATE_INTERVAL = 0.1f;

    protected virtual void OnEnable()
    {
        EditorApplication.update += OnEditorUpdate;
        Undo.undoRedoPerformed += OnUndoRedo;
        lastUpdateTime = EditorApplication.timeSinceStartup;
    }

    protected virtual void OnDisable()
    {
        EditorApplication.update -= OnEditorUpdate;
        Undo.undoRedoPerformed -= OnUndoRedo;
    }

    protected virtual void OnEditorUpdate()
    {
        if (EditorApplication.timeSinceStartup - lastUpdateTime < UPDATE_INTERVAL)
            return;

        if (isDirty)
        {
            RefreshAllComponents();
            isDirty = false;
        }
        lastUpdateTime = EditorApplication.timeSinceStartup;
    }

    protected virtual void RefreshAllComponents()
    {
        if (!serializedObject.targetObject) return;
        
        if (serializedObject.hasModifiedProperties)
        {
            serializedObject.Update();
        }

        var targetObj = target as MonoBehaviour;
        if (targetObj != null && targetObj.isActiveAndEnabled)
        {
            EditorUtility.SetDirty(targetObj);
            
            if (!EditorApplication.isPlaying)
            {
                UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(
                    targetObj.gameObject.scene);
            }
        }

        if (Selection.activeObject == target)
        {
            Repaint();
        }
    }

    protected virtual void OnUndoRedo()
    {
        isDirty = true;
        Repaint();
    }

    protected void MarkDirty()
    {
        if (!isDirty)
        {
            isDirty = true;
            if (target != null)
            {
                EditorUtility.SetDirty(target);
                
                if (serializedObject.hasModifiedProperties)
                {
                    serializedObject.ApplyModifiedProperties();
                }
            }
        }
    }
} 