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

// SortRuleElement is the corresponding interface of SortRuleElement
type SortRuleElement interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetSortOrder returns SortOrder (property field)
	GetSortOrder() SortOrderType
	// GetEventField returns EventField (property field)
	GetEventField() SimpleAttributeOperand
	// IsSortRuleElement is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsSortRuleElement()
	// CreateBuilder creates a SortRuleElementBuilder
	CreateSortRuleElementBuilder() SortRuleElementBuilder
}

// _SortRuleElement is the data-structure of this message
type _SortRuleElement struct {
	ExtensionObjectDefinitionContract
	SortOrder  SortOrderType
	EventField SimpleAttributeOperand
}

var _ SortRuleElement = (*_SortRuleElement)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_SortRuleElement)(nil)

// NewSortRuleElement factory function for _SortRuleElement
func NewSortRuleElement(sortOrder SortOrderType, eventField SimpleAttributeOperand) *_SortRuleElement {
	if eventField == nil {
		panic("eventField of type SimpleAttributeOperand for SortRuleElement must not be nil")
	}
	_result := &_SortRuleElement{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		SortOrder:                         sortOrder,
		EventField:                        eventField,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// SortRuleElementBuilder is a builder for SortRuleElement
type SortRuleElementBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(sortOrder SortOrderType, eventField SimpleAttributeOperand) SortRuleElementBuilder
	// WithSortOrder adds SortOrder (property field)
	WithSortOrder(SortOrderType) SortRuleElementBuilder
	// WithEventField adds EventField (property field)
	WithEventField(SimpleAttributeOperand) SortRuleElementBuilder
	// WithEventFieldBuilder adds EventField (property field) which is build by the builder
	WithEventFieldBuilder(func(SimpleAttributeOperandBuilder) SimpleAttributeOperandBuilder) SortRuleElementBuilder
	// 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 SortRuleElement or returns an error if something is wrong
	Build() (SortRuleElement, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() SortRuleElement
}

// NewSortRuleElementBuilder() creates a SortRuleElementBuilder
func NewSortRuleElementBuilder() SortRuleElementBuilder {
	return &_SortRuleElementBuilder{_SortRuleElement: new(_SortRuleElement)}
}

type _SortRuleElementBuilder struct {
	*_SortRuleElement

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (SortRuleElementBuilder) = (*_SortRuleElementBuilder)(nil)

func (b *_SortRuleElementBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._SortRuleElement
}

func (b *_SortRuleElementBuilder) WithMandatoryFields(sortOrder SortOrderType, eventField SimpleAttributeOperand) SortRuleElementBuilder {
	return b.WithSortOrder(sortOrder).WithEventField(eventField)
}

func (b *_SortRuleElementBuilder) WithSortOrder(sortOrder SortOrderType) SortRuleElementBuilder {
	b.SortOrder = sortOrder
	return b
}

func (b *_SortRuleElementBuilder) WithEventField(eventField SimpleAttributeOperand) SortRuleElementBuilder {
	b.EventField = eventField
	return b
}

func (b *_SortRuleElementBuilder) WithEventFieldBuilder(builderSupplier func(SimpleAttributeOperandBuilder) SimpleAttributeOperandBuilder) SortRuleElementBuilder {
	builder := builderSupplier(b.EventField.CreateSimpleAttributeOperandBuilder())
	var err error
	b.EventField, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "SimpleAttributeOperandBuilder failed"))
	}
	return b
}

func (b *_SortRuleElementBuilder) Build() (SortRuleElement, error) {
	if b.EventField == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'eventField' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._SortRuleElement.deepCopy(), nil
}

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

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

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

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

// CreateSortRuleElementBuilder creates a SortRuleElementBuilder
func (b *_SortRuleElement) CreateSortRuleElementBuilder() SortRuleElementBuilder {
	if b == nil {
		return NewSortRuleElementBuilder()
	}
	return &_SortRuleElementBuilder{_SortRuleElement: b.deepCopy()}
}

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

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

func (m *_SortRuleElement) GetExtensionId() int32 {
	return int32(18650)
}

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

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

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

func (m *_SortRuleElement) GetSortOrder() SortOrderType {
	return m.SortOrder
}

func (m *_SortRuleElement) GetEventField() SimpleAttributeOperand {
	return m.EventField
}

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

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

func (m *_SortRuleElement) GetTypeName() string {
	return "SortRuleElement"
}

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

	// Simple field (sortOrder)
	lengthInBits += 32

	// Simple field (eventField)
	lengthInBits += m.EventField.GetLengthInBits(ctx)

	return lengthInBits
}

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

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

	sortOrder, err := ReadEnumField[SortOrderType](ctx, "sortOrder", "SortOrderType", ReadEnum(SortOrderTypeByValue, ReadUnsignedInt(readBuffer, uint8(32))))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'sortOrder' field"))
	}
	m.SortOrder = sortOrder

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

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

	return m, nil
}

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

		if err := WriteSimpleEnumField[SortOrderType](ctx, "sortOrder", "SortOrderType", m.GetSortOrder(), WriteEnum[SortOrderType, uint32](SortOrderType.GetValue, SortOrderType.PLC4XEnumName, WriteUnsignedInt(writeBuffer, 32))); err != nil {
			return errors.Wrap(err, "Error serializing 'sortOrder' field")
		}

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

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

func (m *_SortRuleElement) IsSortRuleElement() {}

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

func (m *_SortRuleElement) deepCopy() *_SortRuleElement {
	if m == nil {
		return nil
	}
	_SortRuleElementCopy := &_SortRuleElement{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		m.SortOrder,
		utils.DeepCopy[SimpleAttributeOperand](m.EventField),
	}
	_SortRuleElementCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _SortRuleElementCopy
}

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