using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;

namespace Jovian.TagSystem.Editor {

    [InitializeOnLoad]
    public class JovianTagsEditorHistory {
        private readonly int numRecentTags = 20;
        private readonly string saveKey = "EditorSave";
        private readonly string saveDelimiter = "%£&";

        public static JovianTagsEditorHistory Instance { get; }

        public List<string> RecentTags { get; private set; } = new();

        static JovianTagsEditorHistory() {
            Instance = new JovianTagsEditorHistory();
        }

        private JovianTagsEditorHistory() {
            EditorApplication.delayCall += Load;
        }

        public void AddRecentTag(string tag) {
            RecentTags.Insert(0, tag);
            while(RecentTags.Count > numRecentTags) {
                RecentTags.RemoveAt(RecentTags.Count - 1);
            }
            Save();
        }

        private void Load() {
            var saves = EditorPrefs.GetString(Application.productName + saveKey);
            RecentTags = saves.Split(saveDelimiter).ToList();
            if(RecentTags == null) {
                RecentTags = new List<string>();
            }
        }

        private void Save() {
            EditorPrefs.SetString(Application.productName + saveKey, string.Join(saveDelimiter, RecentTags));
        }
    }
}
