﻿#if UNITY_EDITOR

using JLGames.RocketDriver.Actions.Loaderx;
using UnityEditor;
using UnityEngine;

namespace JLGames.RocketDriver.Actions.Component
{
    [CustomEditor(typeof(SpriteData))]
    public class SpriteDataEditor : Editor
    {
        SerializedProperty m_Source;
        SerializedProperty m_SubSprites;

        private void OnEnable()
        {
            m_Source = serializedObject.FindProperty("m_Source");
            m_SubSprites = serializedObject.FindProperty("m_SubSprites");
        }

        public override void OnInspectorGUI()
        {
            EditorGUILayout.PropertyField(m_Source);
            AddUpdateButton();
            GUI.enabled = false;
            EditorGUILayout.PropertyField(m_SubSprites, new GUIContent("Sprite List"));
            GUI.enabled = true;
            serializedObject.ApplyModifiedProperties();
        }

        private void AddUpdateButton()
        {
            if (GUILayout.Button("Update"))
            {
                UpdateSprites();
            }
        }

        private void UpdateSprites()
        {
            m_SubSprites.arraySize = 0;
            if (null == m_Source.objectReferenceValue) return;

            var instanceId = m_Source.objectReferenceInstanceIDValue;
            var path = AssetDatabase.GetAssetPath(instanceId);
            var sprites = EditorUtils.LoadSubAssets(path);
            var size = sprites.Length - 1;
            m_SubSprites.arraySize = size;
            for (var index = 1; index < sprites.Length; index++)
            {
                var sprite = sprites[index];
                m_SubSprites.GetArrayElementAtIndex(index - 1).objectReferenceValue = sprite;
            }
        }
    }
}

#endif