EliteBGS/EDDB/PopulatedSystems.cs

72 lines
2.0 KiB
C#

using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json.Linq;
namespace EliteBGS.EDDB {
public class PopulatedSystems {
private string json_file = null;
private JArray root = null;
private string[] system_names = null;
private Dictionary<string, int> to_id;
public static PopulatedSystems FromFile(string file) {
PopulatedSystems pop = new PopulatedSystems();
string content = File.ReadAllText(file);
pop.json_file = file;
pop.root = JArray.Parse(content);
pop.Initialise();
return pop;
}
private void Initialise() {
MakeSystemNames();
to_id = root.ToDictionary(x => x.Value<string>("name"), x => x.Value<int>("id"));
}
public int ToId(string name) {
return to_id.First(x => string.Compare(x.Key, name, true) == 0).Value;
}
private void MakeSystemNames() {
if (root == null) {
throw new InvalidDataException("no JSON loaded");
}
if (system_names != null && system_names.Length > 0) {
return;
}
var names = root.Children<JObject>().Select(x => x.Value<string>("name"));
system_names = names.ToArray();
}
public string[] SystemNames {
get {
MakeSystemNames();
return system_names;
}
}
public string[] SystemNamesByFilter(string filter) {
MakeSystemNames();
var culture = CultureInfo.InvariantCulture;
return system_names.Where(x => culture.CompareInfo.IndexOf(x, filter, CompareOptions.IgnoreCase) > -1)
.ToArray()
;
}
public string JSONFile {
get => json_file;
}
public JArray Root {
get => root;
}
}
}