LookupGenerator.cs 2.5 KB

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