profile.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/beanzilla/gonode"
  5. )
  6. type Profile struct {
  7. N *gonode.Node `json:"-"`
  8. Pilot string `json:"pilot"`
  9. Playtime float64 `json:"playtime"`
  10. Date Date `json:"date"`
  11. Location Location `json:"location"`
  12. Travel TravelPath `json:"travel"`
  13. }
  14. func (p *Profile) Parse(n *gonode.Node) error {
  15. if !n.HasTag("root") {
  16. return fmt.Errorf("expected 'root' node, got a regular node, invalid node")
  17. }
  18. for kid := range n.Iter() {
  19. txt := fmt.Sprintf("%v", kid.Data())
  20. switch Key(txt) {
  21. case "pilot":
  22. p.Pilot = Value(txt)
  23. case "date":
  24. err := p.Date.Parse(kid)
  25. if err != nil {
  26. return err
  27. }
  28. case "system", "planet":
  29. err := p.Location.Parse(kid)
  30. if err != nil {
  31. return err
  32. }
  33. case "travel", "travel destination", "playtime":
  34. if Key(txt) == "playtime" {
  35. if !IsFloat(Value(txt)) {
  36. return fmt.Errorf("failed parsing playtime, expected float")
  37. }
  38. p.Playtime = ValueFloat64(txt)
  39. }
  40. err := p.Travel.Parse(kid)
  41. if err != nil {
  42. return err
  43. }
  44. }
  45. }
  46. if !p.Location.Valid() {
  47. return fmt.Errorf("didn't find both nodes for location, missing data")
  48. }
  49. p.N = n
  50. return nil
  51. }
  52. func (p *Profile) Update() error {
  53. if p.N == nil {
  54. return fmt.Errorf("missing node, can't update")
  55. }
  56. for kid := range p.N.Iter() {
  57. txt := fmt.Sprintf("%v", kid.Data())
  58. switch Key(txt) {
  59. case "pilot":
  60. kid.SetData(fmt.Sprintf("pilot %s", p.Pilot))
  61. }
  62. }
  63. err := p.Date.Update()
  64. if err != nil {
  65. return err
  66. }
  67. err = p.Location.Update()
  68. if err != nil {
  69. return err
  70. }
  71. err = p.Travel.Update()
  72. if err != nil {
  73. return err
  74. }
  75. return nil
  76. }