/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package model

import (
	"context"
	stdErrors "errors"
	"fmt"

	"github.com/pkg/errors"
	"github.com/rs/zerolog"

	. "github.com/apache/plc4x/plc4go/spi/codegen/fields"
	. "github.com/apache/plc4x/plc4go/spi/codegen/io"
	"github.com/apache/plc4x/plc4go/spi/utils"
)

// Code generated by code-generation. DO NOT EDIT.

// SpanContextDataType is the corresponding interface of SpanContextDataType
type SpanContextDataType interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetTraceId returns TraceId (property field)
	GetTraceId() GuidValue
	// GetSpanId returns SpanId (property field)
	GetSpanId() uint64
	// IsSpanContextDataType is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsSpanContextDataType()
	// CreateBuilder creates a SpanContextDataTypeBuilder
	CreateSpanContextDataTypeBuilder() SpanContextDataTypeBuilder
}

// _SpanContextDataType is the data-structure of this message
type _SpanContextDataType struct {
	ExtensionObjectDefinitionContract
	TraceId GuidValue
	SpanId  uint64
}

var _ SpanContextDataType = (*_SpanContextDataType)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_SpanContextDataType)(nil)

// NewSpanContextDataType factory function for _SpanContextDataType
func NewSpanContextDataType(traceId GuidValue, spanId uint64) *_SpanContextDataType {
	if traceId == nil {
		panic("traceId of type GuidValue for SpanContextDataType must not be nil")
	}
	_result := &_SpanContextDataType{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		TraceId:                           traceId,
		SpanId:                            spanId,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/////////////////////// Builder
///////////////////////

// SpanContextDataTypeBuilder is a builder for SpanContextDataType
type SpanContextDataTypeBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(traceId GuidValue, spanId uint64) SpanContextDataTypeBuilder
	// WithTraceId adds TraceId (property field)
	WithTraceId(GuidValue) SpanContextDataTypeBuilder
	// WithTraceIdBuilder adds TraceId (property field) which is build by the builder
	WithTraceIdBuilder(func(GuidValueBuilder) GuidValueBuilder) SpanContextDataTypeBuilder
	// WithSpanId adds SpanId (property field)
	WithSpanId(uint64) SpanContextDataTypeBuilder
	// Done is used to finish work on this child and return (or create one if none) to the parent builder
	Done() ExtensionObjectDefinitionBuilder
	// Build builds the SpanContextDataType or returns an error if something is wrong
	Build() (SpanContextDataType, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() SpanContextDataType
}

// NewSpanContextDataTypeBuilder() creates a SpanContextDataTypeBuilder
func NewSpanContextDataTypeBuilder() SpanContextDataTypeBuilder {
	return &_SpanContextDataTypeBuilder{_SpanContextDataType: new(_SpanContextDataType)}
}

type _SpanContextDataTypeBuilder struct {
	*_SpanContextDataType

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (SpanContextDataTypeBuilder) = (*_SpanContextDataTypeBuilder)(nil)

func (b *_SpanContextDataTypeBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._SpanContextDataType
}

func (b *_SpanContextDataTypeBuilder) WithMandatoryFields(traceId GuidValue, spanId uint64) SpanContextDataTypeBuilder {
	return b.WithTraceId(traceId).WithSpanId(spanId)
}

func (b *_SpanContextDataTypeBuilder) WithTraceId(traceId GuidValue) SpanContextDataTypeBuilder {
	b.TraceId = traceId
	return b
}

func (b *_SpanContextDataTypeBuilder) WithTraceIdBuilder(builderSupplier func(GuidValueBuilder) GuidValueBuilder) SpanContextDataTypeBuilder {
	builder := builderSupplier(b.TraceId.CreateGuidValueBuilder())
	var err error
	b.TraceId, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "GuidValueBuilder failed"))
	}
	return b
}

func (b *_SpanContextDataTypeBuilder) WithSpanId(spanId uint64) SpanContextDataTypeBuilder {
	b.SpanId = spanId
	return b
}

func (b *_SpanContextDataTypeBuilder) Build() (SpanContextDataType, error) {
	if b.TraceId == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'traceId' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._SpanContextDataType.deepCopy(), nil
}

func (b *_SpanContextDataTypeBuilder) MustBuild() SpanContextDataType {
	build, err := b.Build()
	if err != nil {
		panic(err)
	}
	return build
}

func (b *_SpanContextDataTypeBuilder) Done() ExtensionObjectDefinitionBuilder {
	if b.parentBuilder == nil {
		b.parentBuilder = NewExtensionObjectDefinitionBuilder().(*_ExtensionObjectDefinitionBuilder)
	}
	return b.parentBuilder
}

func (b *_SpanContextDataTypeBuilder) buildForExtensionObjectDefinition() (ExtensionObjectDefinition, error) {
	return b.Build()
}

func (b *_SpanContextDataTypeBuilder) DeepCopy() any {
	_copy := b.CreateSpanContextDataTypeBuilder().(*_SpanContextDataTypeBuilder)
	if b.collectedErr != nil {
		copy(_copy.collectedErr, b.collectedErr)
	}
	return _copy
}

// CreateSpanContextDataTypeBuilder creates a SpanContextDataTypeBuilder
func (b *_SpanContextDataType) CreateSpanContextDataTypeBuilder() SpanContextDataTypeBuilder {
	if b == nil {
		return NewSpanContextDataTypeBuilder()
	}
	return &_SpanContextDataTypeBuilder{_SpanContextDataType: b.deepCopy()}
}

///////////////////////
///////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/////////////////////// Accessors for discriminator values.
///////////////////////

func (m *_SpanContextDataType) GetExtensionId() int32 {
	return int32(19748)
}

///////////////////////
///////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////

func (m *_SpanContextDataType) GetParent() ExtensionObjectDefinitionContract {
	return m.ExtensionObjectDefinitionContract
}

///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/////////////////////// Accessors for property fields.
///////////////////////

func (m *_SpanContextDataType) GetTraceId() GuidValue {
	return m.TraceId
}

func (m *_SpanContextDataType) GetSpanId() uint64 {
	return m.SpanId
}

///////////////////////
///////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////

// Deprecated: use the interface for direct cast
func CastSpanContextDataType(structType any) SpanContextDataType {
	if casted, ok := structType.(SpanContextDataType); ok {
		return casted
	}
	if casted, ok := structType.(*SpanContextDataType); ok {
		return *casted
	}
	return nil
}

func (m *_SpanContextDataType) GetTypeName() string {
	return "SpanContextDataType"
}

func (m *_SpanContextDataType) GetLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).getLengthInBits(ctx))

	// Simple field (traceId)
	lengthInBits += m.TraceId.GetLengthInBits(ctx)

	// Simple field (spanId)
	lengthInBits += 64

	return lengthInBits
}

func (m *_SpanContextDataType) GetLengthInBytes(ctx context.Context) uint16 {
	return m.GetLengthInBits(ctx) / 8
}

func (m *_SpanContextDataType) parse(ctx context.Context, readBuffer utils.ReadBuffer, parent *_ExtensionObjectDefinition, extensionId int32) (__spanContextDataType SpanContextDataType, err error) {
	m.ExtensionObjectDefinitionContract = parent
	parent._SubType = m
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("SpanContextDataType"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for SpanContextDataType")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

	traceId, err := ReadSimpleField[GuidValue](ctx, "traceId", ReadComplex[GuidValue](GuidValueParseWithBuffer, readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'traceId' field"))
	}
	m.TraceId = traceId

	spanId, err := ReadSimpleField(ctx, "spanId", ReadUnsignedLong(readBuffer, uint8(64)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'spanId' field"))
	}
	m.SpanId = spanId

	if closeErr := readBuffer.CloseContext("SpanContextDataType"); closeErr != nil {
		return nil, errors.Wrap(closeErr, "Error closing for SpanContextDataType")
	}

	return m, nil
}

func (m *_SpanContextDataType) Serialize() ([]byte, error) {
	wb := utils.NewWriteBufferByteBased(utils.WithInitialSizeForByteBasedBuffer(int(m.GetLengthInBytes(context.Background()))))
	if err := m.SerializeWithWriteBuffer(context.Background(), wb); err != nil {
		return nil, err
	}
	return wb.GetBytes(), nil
}

func (m *_SpanContextDataType) SerializeWithWriteBuffer(ctx context.Context, writeBuffer utils.WriteBuffer) error {
	positionAware := writeBuffer
	_ = positionAware
	log := zerolog.Ctx(ctx)
	_ = log
	ser := func() error {
		if pushErr := writeBuffer.PushContext("SpanContextDataType"); pushErr != nil {
			return errors.Wrap(pushErr, "Error pushing for SpanContextDataType")
		}

		if err := WriteSimpleField[GuidValue](ctx, "traceId", m.GetTraceId(), WriteComplex[GuidValue](writeBuffer)); err != nil {
			return errors.Wrap(err, "Error serializing 'traceId' field")
		}

		if err := WriteSimpleField[uint64](ctx, "spanId", m.GetSpanId(), WriteUnsignedLong(writeBuffer, 64)); err != nil {
			return errors.Wrap(err, "Error serializing 'spanId' field")
		}

		if popErr := writeBuffer.PopContext("SpanContextDataType"); popErr != nil {
			return errors.Wrap(popErr, "Error popping for SpanContextDataType")
		}
		return nil
	}
	return m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).serializeParent(ctx, writeBuffer, m, ser)
}

func (m *_SpanContextDataType) IsSpanContextDataType() {}

func (m *_SpanContextDataType) DeepCopy() any {
	return m.deepCopy()
}

func (m *_SpanContextDataType) deepCopy() *_SpanContextDataType {
	if m == nil {
		return nil
	}
	_SpanContextDataTypeCopy := &_SpanContextDataType{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[GuidValue](m.TraceId),
		m.SpanId,
	}
	_SpanContextDataTypeCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _SpanContextDataTypeCopy
}

func (m *_SpanContextDataType) String() string {
	if m == nil {
		return "<nil>"
	}
	wb := utils.NewWriteBufferBoxBased(
		utils.WithWriteBufferBoxBasedMergeSingleBoxes(),
		utils.WithWriteBufferBoxBasedOmitEmptyBoxes(),
		utils.WithWriteBufferBoxBasedPrintPosLengthFooter(),
	)
	if err := wb.WriteSerializable(context.Background(), m); err != nil {
		return err.Error()
	}
	return wb.GetBox().String()
}
