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

// QueryFirstRequest is the corresponding interface of QueryFirstRequest
type QueryFirstRequest interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetRequestHeader returns RequestHeader (property field)
	GetRequestHeader() RequestHeader
	// GetView returns View (property field)
	GetView() ViewDescription
	// GetNodeTypes returns NodeTypes (property field)
	GetNodeTypes() []NodeTypeDescription
	// GetFilter returns Filter (property field)
	GetFilter() ContentFilter
	// GetMaxDataSetsToReturn returns MaxDataSetsToReturn (property field)
	GetMaxDataSetsToReturn() uint32
	// GetMaxReferencesToReturn returns MaxReferencesToReturn (property field)
	GetMaxReferencesToReturn() uint32
	// IsQueryFirstRequest is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsQueryFirstRequest()
	// CreateBuilder creates a QueryFirstRequestBuilder
	CreateQueryFirstRequestBuilder() QueryFirstRequestBuilder
}

// _QueryFirstRequest is the data-structure of this message
type _QueryFirstRequest struct {
	ExtensionObjectDefinitionContract
	RequestHeader         RequestHeader
	View                  ViewDescription
	NodeTypes             []NodeTypeDescription
	Filter                ContentFilter
	MaxDataSetsToReturn   uint32
	MaxReferencesToReturn uint32
}

var _ QueryFirstRequest = (*_QueryFirstRequest)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_QueryFirstRequest)(nil)

// NewQueryFirstRequest factory function for _QueryFirstRequest
func NewQueryFirstRequest(requestHeader RequestHeader, view ViewDescription, nodeTypes []NodeTypeDescription, filter ContentFilter, maxDataSetsToReturn uint32, maxReferencesToReturn uint32) *_QueryFirstRequest {
	if requestHeader == nil {
		panic("requestHeader of type RequestHeader for QueryFirstRequest must not be nil")
	}
	if view == nil {
		panic("view of type ViewDescription for QueryFirstRequest must not be nil")
	}
	if filter == nil {
		panic("filter of type ContentFilter for QueryFirstRequest must not be nil")
	}
	_result := &_QueryFirstRequest{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		RequestHeader:                     requestHeader,
		View:                              view,
		NodeTypes:                         nodeTypes,
		Filter:                            filter,
		MaxDataSetsToReturn:               maxDataSetsToReturn,
		MaxReferencesToReturn:             maxReferencesToReturn,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// QueryFirstRequestBuilder is a builder for QueryFirstRequest
type QueryFirstRequestBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(requestHeader RequestHeader, view ViewDescription, nodeTypes []NodeTypeDescription, filter ContentFilter, maxDataSetsToReturn uint32, maxReferencesToReturn uint32) QueryFirstRequestBuilder
	// WithRequestHeader adds RequestHeader (property field)
	WithRequestHeader(RequestHeader) QueryFirstRequestBuilder
	// WithRequestHeaderBuilder adds RequestHeader (property field) which is build by the builder
	WithRequestHeaderBuilder(func(RequestHeaderBuilder) RequestHeaderBuilder) QueryFirstRequestBuilder
	// WithView adds View (property field)
	WithView(ViewDescription) QueryFirstRequestBuilder
	// WithViewBuilder adds View (property field) which is build by the builder
	WithViewBuilder(func(ViewDescriptionBuilder) ViewDescriptionBuilder) QueryFirstRequestBuilder
	// WithNodeTypes adds NodeTypes (property field)
	WithNodeTypes(...NodeTypeDescription) QueryFirstRequestBuilder
	// WithFilter adds Filter (property field)
	WithFilter(ContentFilter) QueryFirstRequestBuilder
	// WithFilterBuilder adds Filter (property field) which is build by the builder
	WithFilterBuilder(func(ContentFilterBuilder) ContentFilterBuilder) QueryFirstRequestBuilder
	// WithMaxDataSetsToReturn adds MaxDataSetsToReturn (property field)
	WithMaxDataSetsToReturn(uint32) QueryFirstRequestBuilder
	// WithMaxReferencesToReturn adds MaxReferencesToReturn (property field)
	WithMaxReferencesToReturn(uint32) QueryFirstRequestBuilder
	// 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 QueryFirstRequest or returns an error if something is wrong
	Build() (QueryFirstRequest, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() QueryFirstRequest
}

// NewQueryFirstRequestBuilder() creates a QueryFirstRequestBuilder
func NewQueryFirstRequestBuilder() QueryFirstRequestBuilder {
	return &_QueryFirstRequestBuilder{_QueryFirstRequest: new(_QueryFirstRequest)}
}

type _QueryFirstRequestBuilder struct {
	*_QueryFirstRequest

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (QueryFirstRequestBuilder) = (*_QueryFirstRequestBuilder)(nil)

func (b *_QueryFirstRequestBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._QueryFirstRequest
}

func (b *_QueryFirstRequestBuilder) WithMandatoryFields(requestHeader RequestHeader, view ViewDescription, nodeTypes []NodeTypeDescription, filter ContentFilter, maxDataSetsToReturn uint32, maxReferencesToReturn uint32) QueryFirstRequestBuilder {
	return b.WithRequestHeader(requestHeader).WithView(view).WithNodeTypes(nodeTypes...).WithFilter(filter).WithMaxDataSetsToReturn(maxDataSetsToReturn).WithMaxReferencesToReturn(maxReferencesToReturn)
}

func (b *_QueryFirstRequestBuilder) WithRequestHeader(requestHeader RequestHeader) QueryFirstRequestBuilder {
	b.RequestHeader = requestHeader
	return b
}

func (b *_QueryFirstRequestBuilder) WithRequestHeaderBuilder(builderSupplier func(RequestHeaderBuilder) RequestHeaderBuilder) QueryFirstRequestBuilder {
	builder := builderSupplier(b.RequestHeader.CreateRequestHeaderBuilder())
	var err error
	b.RequestHeader, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "RequestHeaderBuilder failed"))
	}
	return b
}

func (b *_QueryFirstRequestBuilder) WithView(view ViewDescription) QueryFirstRequestBuilder {
	b.View = view
	return b
}

func (b *_QueryFirstRequestBuilder) WithViewBuilder(builderSupplier func(ViewDescriptionBuilder) ViewDescriptionBuilder) QueryFirstRequestBuilder {
	builder := builderSupplier(b.View.CreateViewDescriptionBuilder())
	var err error
	b.View, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "ViewDescriptionBuilder failed"))
	}
	return b
}

func (b *_QueryFirstRequestBuilder) WithNodeTypes(nodeTypes ...NodeTypeDescription) QueryFirstRequestBuilder {
	b.NodeTypes = nodeTypes
	return b
}

func (b *_QueryFirstRequestBuilder) WithFilter(filter ContentFilter) QueryFirstRequestBuilder {
	b.Filter = filter
	return b
}

func (b *_QueryFirstRequestBuilder) WithFilterBuilder(builderSupplier func(ContentFilterBuilder) ContentFilterBuilder) QueryFirstRequestBuilder {
	builder := builderSupplier(b.Filter.CreateContentFilterBuilder())
	var err error
	b.Filter, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "ContentFilterBuilder failed"))
	}
	return b
}

func (b *_QueryFirstRequestBuilder) WithMaxDataSetsToReturn(maxDataSetsToReturn uint32) QueryFirstRequestBuilder {
	b.MaxDataSetsToReturn = maxDataSetsToReturn
	return b
}

func (b *_QueryFirstRequestBuilder) WithMaxReferencesToReturn(maxReferencesToReturn uint32) QueryFirstRequestBuilder {
	b.MaxReferencesToReturn = maxReferencesToReturn
	return b
}

func (b *_QueryFirstRequestBuilder) Build() (QueryFirstRequest, error) {
	if b.RequestHeader == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'requestHeader' not set"))
	}
	if b.View == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'view' not set"))
	}
	if b.Filter == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'filter' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._QueryFirstRequest.deepCopy(), nil
}

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

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

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

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

// CreateQueryFirstRequestBuilder creates a QueryFirstRequestBuilder
func (b *_QueryFirstRequest) CreateQueryFirstRequestBuilder() QueryFirstRequestBuilder {
	if b == nil {
		return NewQueryFirstRequestBuilder()
	}
	return &_QueryFirstRequestBuilder{_QueryFirstRequest: b.deepCopy()}
}

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

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

func (m *_QueryFirstRequest) GetExtensionId() int32 {
	return int32(615)
}

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

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

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

func (m *_QueryFirstRequest) GetRequestHeader() RequestHeader {
	return m.RequestHeader
}

func (m *_QueryFirstRequest) GetView() ViewDescription {
	return m.View
}

func (m *_QueryFirstRequest) GetNodeTypes() []NodeTypeDescription {
	return m.NodeTypes
}

func (m *_QueryFirstRequest) GetFilter() ContentFilter {
	return m.Filter
}

func (m *_QueryFirstRequest) GetMaxDataSetsToReturn() uint32 {
	return m.MaxDataSetsToReturn
}

func (m *_QueryFirstRequest) GetMaxReferencesToReturn() uint32 {
	return m.MaxReferencesToReturn
}

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

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

func (m *_QueryFirstRequest) GetTypeName() string {
	return "QueryFirstRequest"
}

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

	// Simple field (requestHeader)
	lengthInBits += m.RequestHeader.GetLengthInBits(ctx)

	// Simple field (view)
	lengthInBits += m.View.GetLengthInBits(ctx)

	// Implicit Field (noOfNodeTypes)
	lengthInBits += 32

	// Array field
	if len(m.NodeTypes) > 0 {
		for _curItem, element := range m.NodeTypes {
			arrayCtx := utils.CreateArrayContext(ctx, len(m.NodeTypes), _curItem)
			lengthInBits += element.GetLengthInBits(arrayCtx)
		}
	}

	// Simple field (filter)
	lengthInBits += m.Filter.GetLengthInBits(ctx)

	// Simple field (maxDataSetsToReturn)
	lengthInBits += 32

	// Simple field (maxReferencesToReturn)
	lengthInBits += 32

	return lengthInBits
}

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

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

	requestHeader, err := ReadSimpleField[RequestHeader](ctx, "requestHeader", ReadComplex[RequestHeader](ExtensionObjectDefinitionParseWithBufferProducer[RequestHeader]((int32)(int32(391))), readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'requestHeader' field"))
	}
	m.RequestHeader = requestHeader

	view, err := ReadSimpleField[ViewDescription](ctx, "view", ReadComplex[ViewDescription](ExtensionObjectDefinitionParseWithBufferProducer[ViewDescription]((int32)(int32(513))), readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'view' field"))
	}
	m.View = view

	noOfNodeTypes, err := ReadImplicitField[int32](ctx, "noOfNodeTypes", ReadSignedInt(readBuffer, uint8(32)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'noOfNodeTypes' field"))
	}
	_ = noOfNodeTypes

	nodeTypes, err := ReadCountArrayField[NodeTypeDescription](ctx, "nodeTypes", ReadComplex[NodeTypeDescription](ExtensionObjectDefinitionParseWithBufferProducer[NodeTypeDescription]((int32)(int32(575))), readBuffer), uint64(noOfNodeTypes))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'nodeTypes' field"))
	}
	m.NodeTypes = nodeTypes

	filter, err := ReadSimpleField[ContentFilter](ctx, "filter", ReadComplex[ContentFilter](ExtensionObjectDefinitionParseWithBufferProducer[ContentFilter]((int32)(int32(588))), readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'filter' field"))
	}
	m.Filter = filter

	maxDataSetsToReturn, err := ReadSimpleField(ctx, "maxDataSetsToReturn", ReadUnsignedInt(readBuffer, uint8(32)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'maxDataSetsToReturn' field"))
	}
	m.MaxDataSetsToReturn = maxDataSetsToReturn

	maxReferencesToReturn, err := ReadSimpleField(ctx, "maxReferencesToReturn", ReadUnsignedInt(readBuffer, uint8(32)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'maxReferencesToReturn' field"))
	}
	m.MaxReferencesToReturn = maxReferencesToReturn

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

	return m, nil
}

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

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

		if err := WriteSimpleField[ViewDescription](ctx, "view", m.GetView(), WriteComplex[ViewDescription](writeBuffer)); err != nil {
			return errors.Wrap(err, "Error serializing 'view' field")
		}
		noOfNodeTypes := int32(utils.InlineIf(bool((m.GetNodeTypes()) == (nil)), func() any { return int32(-(int32(1))) }, func() any { return int32(int32(len(m.GetNodeTypes()))) }).(int32))
		if err := WriteImplicitField(ctx, "noOfNodeTypes", noOfNodeTypes, WriteSignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'noOfNodeTypes' field")
		}

		if err := WriteComplexTypeArrayField(ctx, "nodeTypes", m.GetNodeTypes(), writeBuffer); err != nil {
			return errors.Wrap(err, "Error serializing 'nodeTypes' field")
		}

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

		if err := WriteSimpleField[uint32](ctx, "maxDataSetsToReturn", m.GetMaxDataSetsToReturn(), WriteUnsignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'maxDataSetsToReturn' field")
		}

		if err := WriteSimpleField[uint32](ctx, "maxReferencesToReturn", m.GetMaxReferencesToReturn(), WriteUnsignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'maxReferencesToReturn' field")
		}

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

func (m *_QueryFirstRequest) IsQueryFirstRequest() {}

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

func (m *_QueryFirstRequest) deepCopy() *_QueryFirstRequest {
	if m == nil {
		return nil
	}
	_QueryFirstRequestCopy := &_QueryFirstRequest{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[RequestHeader](m.RequestHeader),
		utils.DeepCopy[ViewDescription](m.View),
		utils.DeepCopySlice[NodeTypeDescription, NodeTypeDescription](m.NodeTypes),
		utils.DeepCopy[ContentFilter](m.Filter),
		m.MaxDataSetsToReturn,
		m.MaxReferencesToReturn,
	}
	_QueryFirstRequestCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _QueryFirstRequestCopy
}

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