/*
 * 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.

// RelativePathElement is the corresponding interface of RelativePathElement
type RelativePathElement interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetReferenceTypeId returns ReferenceTypeId (property field)
	GetReferenceTypeId() NodeId
	// GetIncludeSubtypes returns IncludeSubtypes (property field)
	GetIncludeSubtypes() bool
	// GetIsInverse returns IsInverse (property field)
	GetIsInverse() bool
	// GetTargetName returns TargetName (property field)
	GetTargetName() QualifiedName
	// IsRelativePathElement is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsRelativePathElement()
	// CreateBuilder creates a RelativePathElementBuilder
	CreateRelativePathElementBuilder() RelativePathElementBuilder
}

// _RelativePathElement is the data-structure of this message
type _RelativePathElement struct {
	ExtensionObjectDefinitionContract
	ReferenceTypeId NodeId
	IncludeSubtypes bool
	IsInverse       bool
	TargetName      QualifiedName
	// Reserved Fields
	reservedField0 *uint8
}

var _ RelativePathElement = (*_RelativePathElement)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_RelativePathElement)(nil)

// NewRelativePathElement factory function for _RelativePathElement
func NewRelativePathElement(referenceTypeId NodeId, includeSubtypes bool, isInverse bool, targetName QualifiedName) *_RelativePathElement {
	if referenceTypeId == nil {
		panic("referenceTypeId of type NodeId for RelativePathElement must not be nil")
	}
	if targetName == nil {
		panic("targetName of type QualifiedName for RelativePathElement must not be nil")
	}
	_result := &_RelativePathElement{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		ReferenceTypeId:                   referenceTypeId,
		IncludeSubtypes:                   includeSubtypes,
		IsInverse:                         isInverse,
		TargetName:                        targetName,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// RelativePathElementBuilder is a builder for RelativePathElement
type RelativePathElementBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(referenceTypeId NodeId, includeSubtypes bool, isInverse bool, targetName QualifiedName) RelativePathElementBuilder
	// WithReferenceTypeId adds ReferenceTypeId (property field)
	WithReferenceTypeId(NodeId) RelativePathElementBuilder
	// WithReferenceTypeIdBuilder adds ReferenceTypeId (property field) which is build by the builder
	WithReferenceTypeIdBuilder(func(NodeIdBuilder) NodeIdBuilder) RelativePathElementBuilder
	// WithIncludeSubtypes adds IncludeSubtypes (property field)
	WithIncludeSubtypes(bool) RelativePathElementBuilder
	// WithIsInverse adds IsInverse (property field)
	WithIsInverse(bool) RelativePathElementBuilder
	// WithTargetName adds TargetName (property field)
	WithTargetName(QualifiedName) RelativePathElementBuilder
	// WithTargetNameBuilder adds TargetName (property field) which is build by the builder
	WithTargetNameBuilder(func(QualifiedNameBuilder) QualifiedNameBuilder) RelativePathElementBuilder
	// 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 RelativePathElement or returns an error if something is wrong
	Build() (RelativePathElement, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() RelativePathElement
}

// NewRelativePathElementBuilder() creates a RelativePathElementBuilder
func NewRelativePathElementBuilder() RelativePathElementBuilder {
	return &_RelativePathElementBuilder{_RelativePathElement: new(_RelativePathElement)}
}

type _RelativePathElementBuilder struct {
	*_RelativePathElement

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (RelativePathElementBuilder) = (*_RelativePathElementBuilder)(nil)

func (b *_RelativePathElementBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._RelativePathElement
}

func (b *_RelativePathElementBuilder) WithMandatoryFields(referenceTypeId NodeId, includeSubtypes bool, isInverse bool, targetName QualifiedName) RelativePathElementBuilder {
	return b.WithReferenceTypeId(referenceTypeId).WithIncludeSubtypes(includeSubtypes).WithIsInverse(isInverse).WithTargetName(targetName)
}

func (b *_RelativePathElementBuilder) WithReferenceTypeId(referenceTypeId NodeId) RelativePathElementBuilder {
	b.ReferenceTypeId = referenceTypeId
	return b
}

func (b *_RelativePathElementBuilder) WithReferenceTypeIdBuilder(builderSupplier func(NodeIdBuilder) NodeIdBuilder) RelativePathElementBuilder {
	builder := builderSupplier(b.ReferenceTypeId.CreateNodeIdBuilder())
	var err error
	b.ReferenceTypeId, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "NodeIdBuilder failed"))
	}
	return b
}

func (b *_RelativePathElementBuilder) WithIncludeSubtypes(includeSubtypes bool) RelativePathElementBuilder {
	b.IncludeSubtypes = includeSubtypes
	return b
}

func (b *_RelativePathElementBuilder) WithIsInverse(isInverse bool) RelativePathElementBuilder {
	b.IsInverse = isInverse
	return b
}

func (b *_RelativePathElementBuilder) WithTargetName(targetName QualifiedName) RelativePathElementBuilder {
	b.TargetName = targetName
	return b
}

func (b *_RelativePathElementBuilder) WithTargetNameBuilder(builderSupplier func(QualifiedNameBuilder) QualifiedNameBuilder) RelativePathElementBuilder {
	builder := builderSupplier(b.TargetName.CreateQualifiedNameBuilder())
	var err error
	b.TargetName, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "QualifiedNameBuilder failed"))
	}
	return b
}

func (b *_RelativePathElementBuilder) Build() (RelativePathElement, error) {
	if b.ReferenceTypeId == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'referenceTypeId' not set"))
	}
	if b.TargetName == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'targetName' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._RelativePathElement.deepCopy(), nil
}

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

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

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

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

// CreateRelativePathElementBuilder creates a RelativePathElementBuilder
func (b *_RelativePathElement) CreateRelativePathElementBuilder() RelativePathElementBuilder {
	if b == nil {
		return NewRelativePathElementBuilder()
	}
	return &_RelativePathElementBuilder{_RelativePathElement: b.deepCopy()}
}

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

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

func (m *_RelativePathElement) GetExtensionId() int32 {
	return int32(539)
}

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

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

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

func (m *_RelativePathElement) GetReferenceTypeId() NodeId {
	return m.ReferenceTypeId
}

func (m *_RelativePathElement) GetIncludeSubtypes() bool {
	return m.IncludeSubtypes
}

func (m *_RelativePathElement) GetIsInverse() bool {
	return m.IsInverse
}

func (m *_RelativePathElement) GetTargetName() QualifiedName {
	return m.TargetName
}

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

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

func (m *_RelativePathElement) GetTypeName() string {
	return "RelativePathElement"
}

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

	// Simple field (referenceTypeId)
	lengthInBits += m.ReferenceTypeId.GetLengthInBits(ctx)

	// Reserved Field (reserved)
	lengthInBits += 6

	// Simple field (includeSubtypes)
	lengthInBits += 1

	// Simple field (isInverse)
	lengthInBits += 1

	// Simple field (targetName)
	lengthInBits += m.TargetName.GetLengthInBits(ctx)

	return lengthInBits
}

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

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

	referenceTypeId, err := ReadSimpleField[NodeId](ctx, "referenceTypeId", ReadComplex[NodeId](NodeIdParseWithBuffer, readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'referenceTypeId' field"))
	}
	m.ReferenceTypeId = referenceTypeId

	reservedField0, err := ReadReservedField(ctx, "reserved", ReadUnsignedByte(readBuffer, uint8(6)), uint8(0x00))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing reserved field"))
	}
	m.reservedField0 = reservedField0

	includeSubtypes, err := ReadSimpleField(ctx, "includeSubtypes", ReadBoolean(readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'includeSubtypes' field"))
	}
	m.IncludeSubtypes = includeSubtypes

	isInverse, err := ReadSimpleField(ctx, "isInverse", ReadBoolean(readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'isInverse' field"))
	}
	m.IsInverse = isInverse

	targetName, err := ReadSimpleField[QualifiedName](ctx, "targetName", ReadComplex[QualifiedName](QualifiedNameParseWithBuffer, readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'targetName' field"))
	}
	m.TargetName = targetName

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

	return m, nil
}

func (m *_RelativePathElement) 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 *_RelativePathElement) SerializeWithWriteBuffer(ctx context.Context, writeBuffer utils.WriteBuffer) error {
	positionAware := writeBuffer
	_ = positionAware
	log := zerolog.Ctx(ctx)
	_ = log
	ser := func() error {
		if pushErr := writeBuffer.PushContext("RelativePathElement"); pushErr != nil {
			return errors.Wrap(pushErr, "Error pushing for RelativePathElement")
		}

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

		if err := WriteReservedField[uint8](ctx, "reserved", uint8(0x00), WriteUnsignedByte(writeBuffer, 6)); err != nil {
			return errors.Wrap(err, "Error serializing 'reserved' field number 1")
		}

		if err := WriteSimpleField[bool](ctx, "includeSubtypes", m.GetIncludeSubtypes(), WriteBoolean(writeBuffer)); err != nil {
			return errors.Wrap(err, "Error serializing 'includeSubtypes' field")
		}

		if err := WriteSimpleField[bool](ctx, "isInverse", m.GetIsInverse(), WriteBoolean(writeBuffer)); err != nil {
			return errors.Wrap(err, "Error serializing 'isInverse' field")
		}

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

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

func (m *_RelativePathElement) IsRelativePathElement() {}

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

func (m *_RelativePathElement) deepCopy() *_RelativePathElement {
	if m == nil {
		return nil
	}
	_RelativePathElementCopy := &_RelativePathElement{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[NodeId](m.ReferenceTypeId),
		m.IncludeSubtypes,
		m.IsInverse,
		utils.DeepCopy[QualifiedName](m.TargetName),
		m.reservedField0,
	}
	_RelativePathElementCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _RelativePathElementCopy
}

func (m *_RelativePathElement) 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()
}
