Files
notarius/internal/modules/dnd/extract/npcs/canonicalize.go

79 lines
2.2 KiB
Go

package npcs
import (
"sort"
"gitea.maximumdirect.net/eric/notarius/internal/core/source"
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/npcs/identity"
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared"
)
func canonicalizeResponse(response *extractionResponse, order shared.SourceRefOrder, sourceID string) {
if response == nil {
return
}
for index := range response.NPCs {
canonicalizeNPC(&response.NPCs[index], order, sourceID)
}
sort.SliceStable(response.NPCs, func(i, j int) bool {
left, leftOK := order.EarliestValid(canonicalSourceRefs(response.NPCs[i].SourceRefs, sourceID))
right, rightOK := order.EarliestValid(canonicalSourceRefs(response.NPCs[j].SourceRefs, sourceID))
if leftOK != rightOK {
return leftOK
}
if !leftOK {
return false
}
return left < right
})
}
func canonicalizeNPC(npc *npcResponse, order shared.SourceRefOrder, sourceID string) {
if npc == nil {
return
}
npc.SourceRefs = npcResponseRefs(order.Canonicalize(canonicalSourceRefs(npc.SourceRefs, sourceID)))
}
func canonicalNPCList(response extractionResponse, sourceID string) dnd.NPCList {
if response.NPCs == nil {
return dnd.NPCList{NPCs: nil}
}
npcs := make([]dnd.NPC, len(response.NPCs))
for index, npc := range response.NPCs {
npcs[index] = dnd.NPC{
ID: identity.DeriveID(npc.Name),
Name: npc.Name,
SourceRefs: canonicalSourceRefs(npc.SourceRefs, sourceID),
}
}
return dnd.NPCList{NPCs: npcs}
}
func canonicalSourceRefs(values []npcSourceRefResponse, sourceID string) []source.SourceRef {
if values == nil {
return nil
}
out := make([]source.SourceRef, len(values))
for index, value := range values {
out[index] = source.SourceRef{
SourceID: sourceID,
StartUnitID: value.StartUnitID,
EndUnitID: value.EndUnitID,
}
}
return out
}
func npcResponseRefs(values []source.SourceRef) []npcSourceRefResponse {
if values == nil {
return nil
}
out := make([]npcSourceRefResponse, len(values))
for index, value := range values {
out[index] = npcSourceRefResponse{StartUnitID: value.StartUnitID, EndUnitID: value.EndUnitID}
}
return out
}