using System;
using System.Collections.Generic;
using UnityEngine;

namespace Jovian.EncounterSystem {
    [Serializable]
    public class DialogLine {
        public string id;
        [TextArea(2, 6)] public string text;
    }

    /// <summary>Flat registry of reusable dialog lines. Referenced via <see cref="DialogLineRef"/>.</summary>
    [CreateAssetMenu(fileName = "DialogLineLibrary", menuName = "Jovian/Encounter System/Dialog Line Library", order = 4)]
    public class DialogLineLibrary : ScriptableObject {
        public List<DialogLine> lines = new();

        private Dictionary<string, string> cache;

        public string Resolve(string id) {
            if(string.IsNullOrEmpty(id)) {
                return null;
            }

            EnsureCache();
            return cache.GetValueOrDefault(id);
        }

        public void InvalidateCache() {
            cache = null;
        }

        private void EnsureCache() {
            if(cache != null) {
                return;
            }

            cache = new Dictionary<string, string>(lines?.Count ?? 0);
            if(lines == null) {
                return;
            }

            for(int i = 0; i < lines.Count; i++) {
                var line = lines[i];
                if(line != null && !string.IsNullOrEmpty(line.id)) {
                    cache[line.id] = line.text;
                }
            }
        }

#if UNITY_EDITOR
        private void OnValidate() {
            InvalidateCache();
        }
#endif
    }
}
