package serialize

import "code.justin.tv/rhys/nursery/serialize/capnmsg"

//go:generate mkdir -p capnmsg
//go:generate capnp compile -ogo --output=go:capnmsg tal.capnp
//go:generate rm tal.capnp.go

func toCapnp(out *capnmsg.Msg, in *talGolden) error {
	// we can't reset the message to be sure it's safe for reuse
	out.SetKind(capnmsg.MsgKind(in.Kind))
	out.SetTime(in.Time)
	out.SetService(in.Service)
	out.SetMachine(in.Machine)
	out.SetPid(int32(in.PID))
	out.SetTraceid(in.TraceID)
	out.SetSubtraceid(in.SubTraceID)

	desc := capnmsg.NewMsgDescList(out.Segment, len(in.Desc))
	i := 0
	for k, v := range in.Desc {
		item := capnmsg.NewMsgDesc(out.Segment)
		item.SetKey(k)
		item.SetVal(v)
		desc.Set(i, item)
		i++
	}
	out.SetDesc(desc)
	return nil
}

func fromCapnp(out *talGolden, in *capnmsg.Msg) error {
	*out = talGolden{
		Kind:       uint(in.Kind()),
		Time:       in.Time(),
		Service:    in.Service(),
		Machine:    in.Machine(),
		PID:        int(in.Pid()),
		TraceID:    in.Traceid(),
		SubTraceID: in.Subtraceid(),
	}
	desc := in.Desc()
	out.Desc = make(map[string]string, desc.Len())
	for i := 0; i < desc.Len(); i++ {
		item := desc.At(i)
		out.Desc[item.Key()] = item.Val()
	}
	return nil
}
