using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json; using Stackoverflow.Utilities; namespace LibSearchBox { public class IdNotFoundException : Exception { public IdNotFoundException(string message) : base(message) { } } public class IdMap { private int nextId = 0; public BiDictionary map = new BiDictionary(); public Dictionary MapOut { get { Dictionary result = new Dictionary(); foreach (BiDictionary.Pair pair in map) result.Add(pair.First, pair.Second); return result; } } public IdMap() { } public void Import(Dictionary inMap, bool clearOld = true) { // Clear out the old map, if any if(clearOld) map.Clear(); // Import the new records foreach (KeyValuePair pair in inMap) map.Add(pair.Key, pair.Value); // Calculate the next id // FUTURE: Store & retrieve this via JSON nextId = map.Max((pair) => pair.First) + 1; } public int GetId(string pageName) { // Perform unicode normalization pageName = pageName.Normalize(System.Text.NormalizationForm.FormC); int result; if (!map.TryGetBySecond(pageName, out result)) { map.Add(result = nextId++, pageName); } return result; } public string GetPageName(int id) { string result; if (!map.TryGetByFirst(id, out result)) throw new IdNotFoundException($"Error: Couldn't find {id} in the ID map."); return result; } public void MovePageName(string oldPageName, string newPageName) { int id = map.GetBySecond(oldPageName); map.RemoveBySecond(oldPageName); map.Add(id, newPageName); } public int DeletePageName(string pageName) { int id = GetId(pageName); map.RemoveBySecond(pageName); return id; } public override string ToString() { StringBuilder result = new StringBuilder("Id Map:\n"); foreach (BiDictionary.Pair pair in map) result.AppendLine($"\t{pair.First}: {pair.Second}"); return result.ToString(); } } }