using System.Collections.Generic;
using UnityEngine;

namespace Jovian.EncounterSystem {
    /// <summary>Reusable dialog option list. Asset file auto-renames to match <see cref="id"/>.</summary>
    [CreateAssetMenu(fileName = "EncounterDialogOptionSet", menuName = "Jovian/Encounter System/Dialog Option Set", order = 2)]
    public class EncounterDialogOptionSet : ScriptableObject {
        public string id;

        /// <summary>Shared library for every option's <see cref="EncounterDialogOption.text"/> lookup.</summary>
        public DialogLineLibrary library;

        public List<EncounterDialogOption> options;

#if UNITY_EDITOR
        private void OnValidate() {
            if(string.IsNullOrEmpty(id)) {
                return;
            }

            // AssetDatabase calls are unsafe from OnValidate — defer.
            UnityEditor.EditorApplication.delayCall += RenameToMatchId;
        }

        private void RenameToMatchId() {
            if(!this || string.IsNullOrEmpty(id)) {
                return;
            }

            var path = UnityEditor.AssetDatabase.GetAssetPath(this);
            if(string.IsNullOrEmpty(path) || name == id) {
                return;
            }

            var error = UnityEditor.AssetDatabase.RenameAsset(path, id);
            if(!string.IsNullOrEmpty(error)) {
                Debug.LogWarning($"[EncounterDialogOptionSet] Could not rename '{path}' to '{id}': {error}", this);
            }
        }
#endif
    }
}
