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

// QueryNextRequest is the corresponding interface of QueryNextRequest
type QueryNextRequest interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetRequestHeader returns RequestHeader (property field)
	GetRequestHeader() RequestHeader
	// GetReleaseContinuationPoint returns ReleaseContinuationPoint (property field)
	GetReleaseContinuationPoint() bool
	// GetContinuationPoint returns ContinuationPoint (property field)
	GetContinuationPoint() PascalByteString
	// IsQueryNextRequest is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsQueryNextRequest()
	// CreateBuilder creates a QueryNextRequestBuilder
	CreateQueryNextRequestBuilder() QueryNextRequestBuilder
}

// _QueryNextRequest is the data-structure of this message
type _QueryNextRequest struct {
	ExtensionObjectDefinitionContract
	RequestHeader            RequestHeader
	ReleaseContinuationPoint bool
	ContinuationPoint        PascalByteString
	// Reserved Fields
	reservedField0 *uint8
}

var _ QueryNextRequest = (*_QueryNextRequest)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_QueryNextRequest)(nil)

// NewQueryNextRequest factory function for _QueryNextRequest
func NewQueryNextRequest(requestHeader RequestHeader, releaseContinuationPoint bool, continuationPoint PascalByteString) *_QueryNextRequest {
	if requestHeader == nil {
		panic("requestHeader of type RequestHeader for QueryNextRequest must not be nil")
	}
	if continuationPoint == nil {
		panic("continuationPoint of type PascalByteString for QueryNextRequest must not be nil")
	}
	_result := &_QueryNextRequest{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		RequestHeader:                     requestHeader,
		ReleaseContinuationPoint:          releaseContinuationPoint,
		ContinuationPoint:                 continuationPoint,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// QueryNextRequestBuilder is a builder for QueryNextRequest
type QueryNextRequestBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(requestHeader RequestHeader, releaseContinuationPoint bool, continuationPoint PascalByteString) QueryNextRequestBuilder
	// WithRequestHeader adds RequestHeader (property field)
	WithRequestHeader(RequestHeader) QueryNextRequestBuilder
	// WithRequestHeaderBuilder adds RequestHeader (property field) which is build by the builder
	WithRequestHeaderBuilder(func(RequestHeaderBuilder) RequestHeaderBuilder) QueryNextRequestBuilder
	// WithReleaseContinuationPoint adds ReleaseContinuationPoint (property field)
	WithReleaseContinuationPoint(bool) QueryNextRequestBuilder
	// WithContinuationPoint adds ContinuationPoint (property field)
	WithContinuationPoint(PascalByteString) QueryNextRequestBuilder
	// WithContinuationPointBuilder adds ContinuationPoint (property field) which is build by the builder
	WithContinuationPointBuilder(func(PascalByteStringBuilder) PascalByteStringBuilder) QueryNextRequestBuilder
	// 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 QueryNextRequest or returns an error if something is wrong
	Build() (QueryNextRequest, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() QueryNextRequest
}

// NewQueryNextRequestBuilder() creates a QueryNextRequestBuilder
func NewQueryNextRequestBuilder() QueryNextRequestBuilder {
	return &_QueryNextRequestBuilder{_QueryNextRequest: new(_QueryNextRequest)}
}

type _QueryNextRequestBuilder struct {
	*_QueryNextRequest

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (QueryNextRequestBuilder) = (*_QueryNextRequestBuilder)(nil)

func (b *_QueryNextRequestBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._QueryNextRequest
}

func (b *_QueryNextRequestBuilder) WithMandatoryFields(requestHeader RequestHeader, releaseContinuationPoint bool, continuationPoint PascalByteString) QueryNextRequestBuilder {
	return b.WithRequestHeader(requestHeader).WithReleaseContinuationPoint(releaseContinuationPoint).WithContinuationPoint(continuationPoint)
}

func (b *_QueryNextRequestBuilder) WithRequestHeader(requestHeader RequestHeader) QueryNextRequestBuilder {
	b.RequestHeader = requestHeader
	return b
}

func (b *_QueryNextRequestBuilder) WithRequestHeaderBuilder(builderSupplier func(RequestHeaderBuilder) RequestHeaderBuilder) QueryNextRequestBuilder {
	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 *_QueryNextRequestBuilder) WithReleaseContinuationPoint(releaseContinuationPoint bool) QueryNextRequestBuilder {
	b.ReleaseContinuationPoint = releaseContinuationPoint
	return b
}

func (b *_QueryNextRequestBuilder) WithContinuationPoint(continuationPoint PascalByteString) QueryNextRequestBuilder {
	b.ContinuationPoint = continuationPoint
	return b
}

func (b *_QueryNextRequestBuilder) WithContinuationPointBuilder(builderSupplier func(PascalByteStringBuilder) PascalByteStringBuilder) QueryNextRequestBuilder {
	builder := builderSupplier(b.ContinuationPoint.CreatePascalByteStringBuilder())
	var err error
	b.ContinuationPoint, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "PascalByteStringBuilder failed"))
	}
	return b
}

func (b *_QueryNextRequestBuilder) Build() (QueryNextRequest, error) {
	if b.RequestHeader == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'requestHeader' not set"))
	}
	if b.ContinuationPoint == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'continuationPoint' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._QueryNextRequest.deepCopy(), nil
}

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

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

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

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

// CreateQueryNextRequestBuilder creates a QueryNextRequestBuilder
func (b *_QueryNextRequest) CreateQueryNextRequestBuilder() QueryNextRequestBuilder {
	if b == nil {
		return NewQueryNextRequestBuilder()
	}
	return &_QueryNextRequestBuilder{_QueryNextRequest: b.deepCopy()}
}

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

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

func (m *_QueryNextRequest) GetExtensionId() int32 {
	return int32(621)
}

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

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

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

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

func (m *_QueryNextRequest) GetReleaseContinuationPoint() bool {
	return m.ReleaseContinuationPoint
}

func (m *_QueryNextRequest) GetContinuationPoint() PascalByteString {
	return m.ContinuationPoint
}

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

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

func (m *_QueryNextRequest) GetTypeName() string {
	return "QueryNextRequest"
}

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

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

	// Reserved Field (reserved)
	lengthInBits += 7

	// Simple field (releaseContinuationPoint)
	lengthInBits += 1

	// Simple field (continuationPoint)
	lengthInBits += m.ContinuationPoint.GetLengthInBits(ctx)

	return lengthInBits
}

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

func (m *_QueryNextRequest) parse(ctx context.Context, readBuffer utils.ReadBuffer, parent *_ExtensionObjectDefinition, extensionId int32) (__queryNextRequest QueryNextRequest, err error) {
	m.ExtensionObjectDefinitionContract = parent
	parent._SubType = m
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("QueryNextRequest"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for QueryNextRequest")
	}
	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

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

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

	continuationPoint, err := ReadSimpleField[PascalByteString](ctx, "continuationPoint", ReadComplex[PascalByteString](PascalByteStringParseWithBuffer, readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'continuationPoint' field"))
	}
	m.ContinuationPoint = continuationPoint

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

	return m, nil
}

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

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

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

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

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

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

func (m *_QueryNextRequest) IsQueryNextRequest() {}

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

func (m *_QueryNextRequest) deepCopy() *_QueryNextRequest {
	if m == nil {
		return nil
	}
	_QueryNextRequestCopy := &_QueryNextRequest{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[RequestHeader](m.RequestHeader),
		m.ReleaseContinuationPoint,
		utils.DeepCopy[PascalByteString](m.ContinuationPoint),
		m.reservedField0,
	}
	_QueryNextRequestCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _QueryNextRequestCopy
}

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