1package board
2
3import (
4 "fmt"
5
6 "github.com/MichaelMure/git-bug/entities/bug"
7 "github.com/MichaelMure/git-bug/entities/identity"
8 "github.com/MichaelMure/git-bug/entity"
9 "github.com/MichaelMure/git-bug/entity/dag"
10)
11
12// itemEntityType indicate the type of entity board item
13type itemEntityType string
14
15const (
16 entityTypeBug itemEntityType = "bug"
17)
18
19var _ Operation = &AddItemEntityOperation{}
20
21type AddItemEntityOperation struct {
22 dag.OpBase
23 ColumnId entity.Id `json:"column"`
24 EntityType itemEntityType `json:"entity_type"`
25 EntityId entity.Id `json:"entity_id"`
26 entity entity.Interface // not serialized
27}
28
29func (op *AddItemEntityOperation) Id() entity.Id {
30 return dag.IdOperation(op, &op.OpBase)
31}
32
33func (op *AddItemEntityOperation) Validate() error {
34 if err := op.OpBase.Validate(op, AddItemEntityOp); err != nil {
35 return err
36 }
37
38 if err := op.ColumnId.Validate(); err != nil {
39 return err
40 }
41
42 switch op.EntityType {
43 case entityTypeBug:
44 default:
45 return fmt.Errorf("unknown entity type")
46 }
47
48 if err := op.EntityId.Validate(); err != nil {
49 return err
50 }
51
52 return nil
53}
54
55func (op *AddItemEntityOperation) Apply(snapshot *Snapshot) {
56 if op.entity == nil {
57 return
58 }
59
60 snapshot.addActor(op.Author())
61
62 for _, column := range snapshot.Columns {
63 if column.Id == op.ColumnId {
64 switch e := op.entity.(type) {
65 case bug.Interface:
66 column.Items = append(column.Items, &BugItem{
67 combinedId: entity.CombineIds(snapshot.Id(), e.Id()),
68 bug: e,
69 })
70 }
71 return
72 }
73 }
74}
75
76func NewAddItemEntityOp(author identity.Interface, unixTime int64, columnId entity.Id, e entity.Interface) *AddItemEntityOperation {
77 switch e := e.(type) {
78 case bug.Interface:
79 return &AddItemEntityOperation{
80 OpBase: dag.NewOpBase(AddItemEntityOp, author, unixTime),
81 ColumnId: columnId,
82 EntityType: entityTypeBug,
83 EntityId: e.Id(),
84 entity: e,
85 }
86 default:
87 panic("invalid entity type")
88 }
89}
90
91// AddItemEntity is a convenience function to add an entity item to a Board
92func AddItemEntity(b Interface, author identity.Interface, unixTime int64, columnId entity.Id, e entity.Interface, metadata map[string]string) (entity.CombinedId, *AddItemEntityOperation, error) {
93 op := NewAddItemEntityOp(author, unixTime, columnId, e)
94 for key, val := range metadata {
95 op.SetMetadata(key, val)
96 }
97 if err := op.Validate(); err != nil {
98 return entity.UnsetCombinedId, nil, err
99 }
100 b.Append(op)
101 return entity.CombineIds(b.Id(), op.Id()), op, nil
102}