package pbmsg

import (
	"encoding/binary"
	"fmt"
)

// TransactionID is an identifier for a collection of events as one
// transaction
type TransactionID [2]uint64

// String produces a string representation of the transaction ID: the
// hex value of the bytes of the ID, with the least significant bits
// first.
func (tid TransactionID) String() string {
	return fmt.Sprintf("%x", tid.Bytes())
}

func (tid TransactionID) Bytes() []byte {
	bytes := make([]byte, 16)
	binary.LittleEndian.PutUint64(bytes[:8], tid[0])
	binary.LittleEndian.PutUint64(bytes[8:], tid[1])
	return bytes
}

func IDForEvent(ev *Event) *TransactionID {
	evid := ev.GetTransactionId()
	switch len(evid) {
	case 0:
		return &TransactionID{0, 0}
	case 1:
		return &TransactionID{0, ev.TransactionId[0]}
	default:
		return &TransactionID{ev.TransactionId[0], ev.TransactionId[1]}
	}
}

func IDForTx(tx *Transaction) TransactionID {
	txid := tx.GetTransactionId()
	switch len(txid) {
	case 0:
		return TransactionID{0, 0}
	case 1:
		return TransactionID{0, tx.TransactionId[0]}
	default:
		return TransactionID{tx.TransactionId[0], tx.TransactionId[1]}

	}
}
