package tx

import (
	"encoding/binary"
	"fmt"

	"code.justin.tv/release/trace/api"
	"code.justin.tv/release/trace/events"
)

// 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 *events.Event) *TransactionID {
	var evid []uint64
	if ev != nil {
		evid = ev.TransactionId
	}
	switch len(evid) {
	case 0:
		return &TransactionID{0, 0}
	case 1:
		return &TransactionID{0, evid[0]}
	default:
		return &TransactionID{evid[0], evid[1]}
	}
}

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

	}
}
