SearchBox/SearchBox/IdMap.cs

88 lines
2.1 KiB
C#

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<int, string> map = new BiDictionary<int, string>();
public Dictionary<int, string> MapOut {
get {
Dictionary<int, string> result = new Dictionary<int, string>();
foreach (BiDictionary<int, string>.Pair pair in map)
result.Add(pair.First, pair.Second);
return result;
}
}
public IdMap()
{
}
public void Import(Dictionary<int, string> inMap, bool clearOld = true) {
// Clear out the old map, if any
if(clearOld) map.Clear();
// Import the new records
foreach (KeyValuePair<int, string> 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<int, string>.Pair pair in map)
result.AppendLine($"\t{pair.First}: {pair.Second}");
return result.ToString();
}
}
}