using System;
using System.Collections.Generic;

namespace Jovian.EncounterSystem {
    public enum QuestLogEventType {
        Started,
        Advanced,
        Completed
    }

    [Serializable]
    public class QuestLogEntry {
        public QuestLogEventType type;
        public string encounterInternalId;
        public string encounterName;
        public string fromEncounterName;
    }

    /// <summary>
    /// Chronological, serialisable record of quest events. Subscribes at construction —
    /// build before any encounter fires or early entries will be missed.
    /// </summary>
    public class QuestLog {
        private readonly List<QuestLogEntry> entries = new();

        public IReadOnlyList<QuestLogEntry> Entries => entries;

        public QuestLog(QuestProgress progress) {
            progress.QuestStarted += quest => Record(QuestLogEventType.Started, null, quest);
            progress.QuestAdvanced += (from, to) => Record(QuestLogEventType.Advanced, from, to);
            progress.QuestCompleted += quest => Record(QuestLogEventType.Completed, null, quest);
        }

        public List<QuestLogEntry> CreateSnapshot() {
            return new List<QuestLogEntry>(entries);
        }

        public void Restore(IEnumerable<QuestLogEntry> saved) {
            entries.Clear();
            if(saved == null) {
                return;
            }

            entries.AddRange(saved);
        }

        public IEnumerable<string> ResolvedEncounterIds() {
            for(int i = 0; i < entries.Count; i++) {
                var id = entries[i].encounterInternalId;
                if(!string.IsNullOrEmpty(id)) {
                    yield return id;
                }
            }
        }

        private void Record(QuestLogEventType type, IEncounter from, IEncounter to) {
            entries.Add(new QuestLogEntry {
                type = type,
                encounterInternalId = to?.EncounterDefinition?.internalId,
                encounterName = to?.EncounterDefinition?.name,
                fromEncounterName = from?.EncounterDefinition?.name
            });
        }
    }
}
