package modelse

import "strconv"

const (
	HASH_SIZE_8   = 8
	HASH_SIZE_16  = 16
	HASH_SIZE_128 = 128
)

// apm_span_context
type ApmSpanContextT struct {
	type_from      [1]byte
	sample         [1]byte
	host_id        [8]byte
	app_id         [8]byte
	instance_id    [8]byte
	trace_id       [16]byte
	assumed_app_id [8]byte
	span_id        [8]byte
}

type HashByte [HASH_SIZE_8]byte

type HashByte16 [HASH_SIZE_16]byte

type HashByte128 [HASH_SIZE_128]byte

type INT_HASH_ID struct {
	IntVal   int64
	HashtVal HashByte
}

type ID_STRING string

func (id ID_STRING) ToString() string {
	return string(id)
}

func (id ID_STRING) ToInt64() (int64, error) {
	intID, err := strconv.ParseInt(id.ToString(), 10, 64)
	if err != nil {
		return 0, err
	}
	return intID, nil
}

func (id ID_STRING) ToHashByte() HashByte {
	var charArray HashByte
	hexStringToBPFBytes(id.ToString(), &charArray)
	return charArray
}

func hexStringToBPFBytes(str string, out *HashByte) {
	for i := 0; i < len(str)/2; i++ {
		ch0 := str[2*i]
		ch1 := str[2*i+1]
		nib0 := (ch0 & 0x0F) + (ch0 >> 6) | ((ch0 >> 3) & 0x08)
		nib1 := (ch1 & 0x0F) + (ch1 >> 6) | ((ch1 >> 3) & 0x08)
		(*out)[i] = (nib0 << 4) | nib1
	}
}
