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

// ReadEventDetailsSorted is the corresponding interface of ReadEventDetailsSorted
type ReadEventDetailsSorted interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetNumValuesPerNode returns NumValuesPerNode (property field)
	GetNumValuesPerNode() uint32
	// GetStartTime returns StartTime (property field)
	GetStartTime() int64
	// GetEndTime returns EndTime (property field)
	GetEndTime() int64
	// GetFilter returns Filter (property field)
	GetFilter() EventFilter
	// GetSortClause returns SortClause (property field)
	GetSortClause() []SortRuleElement
	// IsReadEventDetailsSorted is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsReadEventDetailsSorted()
	// CreateBuilder creates a ReadEventDetailsSortedBuilder
	CreateReadEventDetailsSortedBuilder() ReadEventDetailsSortedBuilder
}

// _ReadEventDetailsSorted is the data-structure of this message
type _ReadEventDetailsSorted struct {
	ExtensionObjectDefinitionContract
	NumValuesPerNode uint32
	StartTime        int64
	EndTime          int64
	Filter           EventFilter
	SortClause       []SortRuleElement
}

var _ ReadEventDetailsSorted = (*_ReadEventDetailsSorted)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_ReadEventDetailsSorted)(nil)

// NewReadEventDetailsSorted factory function for _ReadEventDetailsSorted
func NewReadEventDetailsSorted(numValuesPerNode uint32, startTime int64, endTime int64, filter EventFilter, sortClause []SortRuleElement) *_ReadEventDetailsSorted {
	if filter == nil {
		panic("filter of type EventFilter for ReadEventDetailsSorted must not be nil")
	}
	_result := &_ReadEventDetailsSorted{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		NumValuesPerNode:                  numValuesPerNode,
		StartTime:                         startTime,
		EndTime:                           endTime,
		Filter:                            filter,
		SortClause:                        sortClause,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// ReadEventDetailsSortedBuilder is a builder for ReadEventDetailsSorted
type ReadEventDetailsSortedBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(numValuesPerNode uint32, startTime int64, endTime int64, filter EventFilter, sortClause []SortRuleElement) ReadEventDetailsSortedBuilder
	// WithNumValuesPerNode adds NumValuesPerNode (property field)
	WithNumValuesPerNode(uint32) ReadEventDetailsSortedBuilder
	// WithStartTime adds StartTime (property field)
	WithStartTime(int64) ReadEventDetailsSortedBuilder
	// WithEndTime adds EndTime (property field)
	WithEndTime(int64) ReadEventDetailsSortedBuilder
	// WithFilter adds Filter (property field)
	WithFilter(EventFilter) ReadEventDetailsSortedBuilder
	// WithFilterBuilder adds Filter (property field) which is build by the builder
	WithFilterBuilder(func(EventFilterBuilder) EventFilterBuilder) ReadEventDetailsSortedBuilder
	// WithSortClause adds SortClause (property field)
	WithSortClause(...SortRuleElement) ReadEventDetailsSortedBuilder
	// 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 ReadEventDetailsSorted or returns an error if something is wrong
	Build() (ReadEventDetailsSorted, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() ReadEventDetailsSorted
}

// NewReadEventDetailsSortedBuilder() creates a ReadEventDetailsSortedBuilder
func NewReadEventDetailsSortedBuilder() ReadEventDetailsSortedBuilder {
	return &_ReadEventDetailsSortedBuilder{_ReadEventDetailsSorted: new(_ReadEventDetailsSorted)}
}

type _ReadEventDetailsSortedBuilder struct {
	*_ReadEventDetailsSorted

	parentBuilder *_ExtensionObjectDefinitionBuilder

	err *utils.MultiError
}

var _ (ReadEventDetailsSortedBuilder) = (*_ReadEventDetailsSortedBuilder)(nil)

func (b *_ReadEventDetailsSortedBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._ReadEventDetailsSorted
}

func (b *_ReadEventDetailsSortedBuilder) WithMandatoryFields(numValuesPerNode uint32, startTime int64, endTime int64, filter EventFilter, sortClause []SortRuleElement) ReadEventDetailsSortedBuilder {
	return b.WithNumValuesPerNode(numValuesPerNode).WithStartTime(startTime).WithEndTime(endTime).WithFilter(filter).WithSortClause(sortClause...)
}

func (b *_ReadEventDetailsSortedBuilder) WithNumValuesPerNode(numValuesPerNode uint32) ReadEventDetailsSortedBuilder {
	b.NumValuesPerNode = numValuesPerNode
	return b
}

func (b *_ReadEventDetailsSortedBuilder) WithStartTime(startTime int64) ReadEventDetailsSortedBuilder {
	b.StartTime = startTime
	return b
}

func (b *_ReadEventDetailsSortedBuilder) WithEndTime(endTime int64) ReadEventDetailsSortedBuilder {
	b.EndTime = endTime
	return b
}

func (b *_ReadEventDetailsSortedBuilder) WithFilter(filter EventFilter) ReadEventDetailsSortedBuilder {
	b.Filter = filter
	return b
}

func (b *_ReadEventDetailsSortedBuilder) WithFilterBuilder(builderSupplier func(EventFilterBuilder) EventFilterBuilder) ReadEventDetailsSortedBuilder {
	builder := builderSupplier(b.Filter.CreateEventFilterBuilder())
	var err error
	b.Filter, err = builder.Build()
	if err != nil {
		if b.err == nil {
			b.err = &utils.MultiError{MainError: errors.New("sub builder failed")}
		}
		b.err.Append(errors.Wrap(err, "EventFilterBuilder failed"))
	}
	return b
}

func (b *_ReadEventDetailsSortedBuilder) WithSortClause(sortClause ...SortRuleElement) ReadEventDetailsSortedBuilder {
	b.SortClause = sortClause
	return b
}

func (b *_ReadEventDetailsSortedBuilder) Build() (ReadEventDetailsSorted, error) {
	if b.Filter == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'filter' not set"))
	}
	if b.err != nil {
		return nil, errors.Wrap(b.err, "error occurred during build")
	}
	return b._ReadEventDetailsSorted.deepCopy(), nil
}

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

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

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

func (b *_ReadEventDetailsSortedBuilder) DeepCopy() any {
	_copy := b.CreateReadEventDetailsSortedBuilder().(*_ReadEventDetailsSortedBuilder)
	if b.err != nil {
		_copy.err = b.err.DeepCopy().(*utils.MultiError)
	}
	return _copy
}

// CreateReadEventDetailsSortedBuilder creates a ReadEventDetailsSortedBuilder
func (b *_ReadEventDetailsSorted) CreateReadEventDetailsSortedBuilder() ReadEventDetailsSortedBuilder {
	if b == nil {
		return NewReadEventDetailsSortedBuilder()
	}
	return &_ReadEventDetailsSortedBuilder{_ReadEventDetailsSorted: b.deepCopy()}
}

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

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

func (m *_ReadEventDetailsSorted) GetExtensionId() int32 {
	return int32(18651)
}

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

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

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

func (m *_ReadEventDetailsSorted) GetNumValuesPerNode() uint32 {
	return m.NumValuesPerNode
}

func (m *_ReadEventDetailsSorted) GetStartTime() int64 {
	return m.StartTime
}

func (m *_ReadEventDetailsSorted) GetEndTime() int64 {
	return m.EndTime
}

func (m *_ReadEventDetailsSorted) GetFilter() EventFilter {
	return m.Filter
}

func (m *_ReadEventDetailsSorted) GetSortClause() []SortRuleElement {
	return m.SortClause
}

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

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

func (m *_ReadEventDetailsSorted) GetTypeName() string {
	return "ReadEventDetailsSorted"
}

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

	// Simple field (numValuesPerNode)
	lengthInBits += 32

	// Simple field (startTime)
	lengthInBits += 64

	// Simple field (endTime)
	lengthInBits += 64

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

	// Implicit Field (noOfSortClause)
	lengthInBits += 32

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

	return lengthInBits
}

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

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

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

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

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

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

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

	sortClause, err := ReadCountArrayField[SortRuleElement](ctx, "sortClause", ReadComplex[SortRuleElement](ExtensionObjectDefinitionParseWithBufferProducer[SortRuleElement]((int32)(int32(18650))), readBuffer), uint64(noOfSortClause))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'sortClause' field"))
	}
	m.SortClause = sortClause

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

	return m, nil
}

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

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

		if err := WriteSimpleField[int64](ctx, "startTime", m.GetStartTime(), WriteSignedLong(writeBuffer, 64)); err != nil {
			return errors.Wrap(err, "Error serializing 'startTime' field")
		}

		if err := WriteSimpleField[int64](ctx, "endTime", m.GetEndTime(), WriteSignedLong(writeBuffer, 64)); err != nil {
			return errors.Wrap(err, "Error serializing 'endTime' field")
		}

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

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

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

func (m *_ReadEventDetailsSorted) IsReadEventDetailsSorted() {}

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

func (m *_ReadEventDetailsSorted) deepCopy() *_ReadEventDetailsSorted {
	if m == nil {
		return nil
	}
	_ReadEventDetailsSortedCopy := &_ReadEventDetailsSorted{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		m.NumValuesPerNode,
		m.StartTime,
		m.EndTime,
		utils.DeepCopy[EventFilter](m.Filter),
		utils.DeepCopySlice[SortRuleElement, SortRuleElement](m.SortClause),
	}
	_ReadEventDetailsSortedCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _ReadEventDetailsSortedCopy
}

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