LookupGenerator.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Collections.Generic;
  3. namespace InABox.Core
  4. {
  5. public abstract class LookupGenerator<T> : ILookupGenerator
  6. {
  7. private readonly List<Tuple<string, Type>> columns = new List<Tuple<string, Type>>();
  8. private readonly List<LookupEntry> entries = new List<LookupEntry>();
  9. public LookupGenerator(T[]? items)
  10. {
  11. Items = items;
  12. }
  13. /// <summary>
  14. /// Null is synonymous with an empty list.
  15. /// </summary>
  16. public T[]? Items { get; set; }
  17. public event GenerateLookupsHandler? OnBeforeGenerateLookups;
  18. public event GenerateLookupsHandler? OnAfterGenerateLookups;
  19. public CoreTable AsTable(string colname)
  20. {
  21. var result = new CoreTable();
  22. result.Columns.Add(new CoreColumn { ColumnName = colname, DataType = typeof(object) });
  23. result.Columns.Add(new CoreColumn { ColumnName = "Display", DataType = typeof(string) });
  24. foreach (var column in columns)
  25. result.Columns.Add(new CoreColumn { ColumnName = column.Item1, DataType = column.Item2 });
  26. GenerateLookups();
  27. foreach (var entry in entries)
  28. {
  29. var row = result.NewRow();
  30. row[colname] = entry.Key;
  31. row["Display"] = entry.Display;
  32. for (var i = 0; i < columns.Count; i++)
  33. row[columns[i].Item1] = entry.Values[i];
  34. result.Rows.Add(row);
  35. }
  36. return result;
  37. }
  38. private void GenerateLookups()
  39. {
  40. OnBeforeGenerateLookups?.Invoke(this, entries);
  41. DoGenerateLookups();
  42. OnAfterGenerateLookups?.Invoke(this, entries);
  43. }
  44. protected virtual void DoGenerateLookups()
  45. {
  46. }
  47. protected void Clear()
  48. {
  49. entries.Clear();
  50. }
  51. protected LookupEntry AddValue(object key, string display, params object[] values)
  52. {
  53. if (values.Length != columns.Count)
  54. throw new Exception("Incorrect # of values in " + GetType().Name);
  55. var result = new LookupEntry(key, display, values);
  56. entries.Add(result);
  57. return result;
  58. }
  59. protected void AddColumn(string name, Type type)
  60. {
  61. columns.Add(new Tuple<string, Type>(name, type));
  62. }
  63. }
  64. }