catalog.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package main
  2. import (
  3. "encoding/json"
  4. "os"
  5. "path/filepath"
  6. "strings"
  7. )
  8. type Catalog struct {
  9. Tiles []Tile
  10. }
  11. func (c *Catalog) LoadFile(filename string) error {
  12. pay, err := os.ReadFile(filename)
  13. if err != nil {
  14. return err
  15. }
  16. file := []map[string]any{}
  17. err = json.Unmarshal(pay, &file)
  18. if err != nil {
  19. return err
  20. }
  21. for _, m := range file {
  22. t := TileFromMap(m)
  23. if t == nil {
  24. continue
  25. }
  26. c.Tiles = append(c.Tiles, t)
  27. }
  28. return nil
  29. }
  30. func (c *Catalog) LoadTiles(dirname string) error {
  31. ls, err := os.ReadDir(dirname)
  32. if err != nil {
  33. return err
  34. }
  35. for _, ent := range ls {
  36. // Ignore: hidden, dirs, non json, template
  37. if strings.HasPrefix(ent.Name(), ".") || ent.IsDir() || !strings.HasSuffix(ent.Name(), ".json") || ent.Name() == "0_template.json" {
  38. continue
  39. }
  40. err = c.LoadFile(filepath.Join(dirname, ent.Name()))
  41. if err != nil {
  42. return err
  43. }
  44. }
  45. return nil
  46. }
  47. func (c *Catalog) FindByName(name string) (int, bool) {
  48. for idx, t := range c.Tiles {
  49. if t.Name() == name {
  50. return idx, true
  51. }
  52. }
  53. return 0, false
  54. }
  55. func (c *Catalog) Symbol(idx int) string {
  56. return c.Tiles[idx].Symbol()
  57. }
  58. func (c *Catalog) Color(idx int) string {
  59. return c.Tiles[idx].Color()
  60. }
  61. func (c *Catalog) Next(idx int) {
  62. c.Tiles[idx].Next()
  63. }
  64. func (c *Catalog) MakeTemplate(filename string) error {
  65. pay, err := json.MarshalIndent([]map[string]any{
  66. {
  67. "name": "template",
  68. "symbol": "0",
  69. "color": "BRI BRO ON BLA",
  70. },
  71. {
  72. "name": "animated-template",
  73. "symbols": []string{
  74. "1",
  75. "2",
  76. "3",
  77. },
  78. "colors": []string{
  79. "BRI RED ON BLA",
  80. "BRI GRE ON BLA",
  81. "BRI CYA ON BLA",
  82. },
  83. "update": []string{
  84. "time 150ms",
  85. },
  86. },
  87. }, "", " ")
  88. if err != nil {
  89. return err
  90. }
  91. err = os.WriteFile(filename, pay, 0666)
  92. return err
  93. }