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

// PublishedEventsDataType is the corresponding interface of PublishedEventsDataType
type PublishedEventsDataType interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetEventNotifier returns EventNotifier (property field)
	GetEventNotifier() NodeId
	// GetSelectedFields returns SelectedFields (property field)
	GetSelectedFields() []SimpleAttributeOperand
	// GetFilter returns Filter (property field)
	GetFilter() ContentFilter
	// IsPublishedEventsDataType is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsPublishedEventsDataType()
	// CreateBuilder creates a PublishedEventsDataTypeBuilder
	CreatePublishedEventsDataTypeBuilder() PublishedEventsDataTypeBuilder
}

// _PublishedEventsDataType is the data-structure of this message
type _PublishedEventsDataType struct {
	ExtensionObjectDefinitionContract
	EventNotifier  NodeId
	SelectedFields []SimpleAttributeOperand
	Filter         ContentFilter
}

var _ PublishedEventsDataType = (*_PublishedEventsDataType)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_PublishedEventsDataType)(nil)

// NewPublishedEventsDataType factory function for _PublishedEventsDataType
func NewPublishedEventsDataType(eventNotifier NodeId, selectedFields []SimpleAttributeOperand, filter ContentFilter) *_PublishedEventsDataType {
	if eventNotifier == nil {
		panic("eventNotifier of type NodeId for PublishedEventsDataType must not be nil")
	}
	if filter == nil {
		panic("filter of type ContentFilter for PublishedEventsDataType must not be nil")
	}
	_result := &_PublishedEventsDataType{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		EventNotifier:                     eventNotifier,
		SelectedFields:                    selectedFields,
		Filter:                            filter,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// PublishedEventsDataTypeBuilder is a builder for PublishedEventsDataType
type PublishedEventsDataTypeBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(eventNotifier NodeId, selectedFields []SimpleAttributeOperand, filter ContentFilter) PublishedEventsDataTypeBuilder
	// WithEventNotifier adds EventNotifier (property field)
	WithEventNotifier(NodeId) PublishedEventsDataTypeBuilder
	// WithEventNotifierBuilder adds EventNotifier (property field) which is build by the builder
	WithEventNotifierBuilder(func(NodeIdBuilder) NodeIdBuilder) PublishedEventsDataTypeBuilder
	// WithSelectedFields adds SelectedFields (property field)
	WithSelectedFields(...SimpleAttributeOperand) PublishedEventsDataTypeBuilder
	// WithFilter adds Filter (property field)
	WithFilter(ContentFilter) PublishedEventsDataTypeBuilder
	// WithFilterBuilder adds Filter (property field) which is build by the builder
	WithFilterBuilder(func(ContentFilterBuilder) ContentFilterBuilder) PublishedEventsDataTypeBuilder
	// 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 PublishedEventsDataType or returns an error if something is wrong
	Build() (PublishedEventsDataType, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() PublishedEventsDataType
}

// NewPublishedEventsDataTypeBuilder() creates a PublishedEventsDataTypeBuilder
func NewPublishedEventsDataTypeBuilder() PublishedEventsDataTypeBuilder {
	return &_PublishedEventsDataTypeBuilder{_PublishedEventsDataType: new(_PublishedEventsDataType)}
}

type _PublishedEventsDataTypeBuilder struct {
	*_PublishedEventsDataType

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (PublishedEventsDataTypeBuilder) = (*_PublishedEventsDataTypeBuilder)(nil)

func (b *_PublishedEventsDataTypeBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._PublishedEventsDataType
}

func (b *_PublishedEventsDataTypeBuilder) WithMandatoryFields(eventNotifier NodeId, selectedFields []SimpleAttributeOperand, filter ContentFilter) PublishedEventsDataTypeBuilder {
	return b.WithEventNotifier(eventNotifier).WithSelectedFields(selectedFields...).WithFilter(filter)
}

func (b *_PublishedEventsDataTypeBuilder) WithEventNotifier(eventNotifier NodeId) PublishedEventsDataTypeBuilder {
	b.EventNotifier = eventNotifier
	return b
}

func (b *_PublishedEventsDataTypeBuilder) WithEventNotifierBuilder(builderSupplier func(NodeIdBuilder) NodeIdBuilder) PublishedEventsDataTypeBuilder {
	builder := builderSupplier(b.EventNotifier.CreateNodeIdBuilder())
	var err error
	b.EventNotifier, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "NodeIdBuilder failed"))
	}
	return b
}

func (b *_PublishedEventsDataTypeBuilder) WithSelectedFields(selectedFields ...SimpleAttributeOperand) PublishedEventsDataTypeBuilder {
	b.SelectedFields = selectedFields
	return b
}

func (b *_PublishedEventsDataTypeBuilder) WithFilter(filter ContentFilter) PublishedEventsDataTypeBuilder {
	b.Filter = filter
	return b
}

func (b *_PublishedEventsDataTypeBuilder) WithFilterBuilder(builderSupplier func(ContentFilterBuilder) ContentFilterBuilder) PublishedEventsDataTypeBuilder {
	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 *_PublishedEventsDataTypeBuilder) Build() (PublishedEventsDataType, error) {
	if b.EventNotifier == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'eventNotifier' 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._PublishedEventsDataType.deepCopy(), nil
}

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

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

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

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

// CreatePublishedEventsDataTypeBuilder creates a PublishedEventsDataTypeBuilder
func (b *_PublishedEventsDataType) CreatePublishedEventsDataTypeBuilder() PublishedEventsDataTypeBuilder {
	if b == nil {
		return NewPublishedEventsDataTypeBuilder()
	}
	return &_PublishedEventsDataTypeBuilder{_PublishedEventsDataType: b.deepCopy()}
}

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

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

func (m *_PublishedEventsDataType) GetExtensionId() int32 {
	return int32(15584)
}

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

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

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

func (m *_PublishedEventsDataType) GetEventNotifier() NodeId {
	return m.EventNotifier
}

func (m *_PublishedEventsDataType) GetSelectedFields() []SimpleAttributeOperand {
	return m.SelectedFields
}

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

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

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

func (m *_PublishedEventsDataType) GetTypeName() string {
	return "PublishedEventsDataType"
}

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

	// Simple field (eventNotifier)
	lengthInBits += m.EventNotifier.GetLengthInBits(ctx)

	// Implicit Field (noOfSelectedFields)
	lengthInBits += 32

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

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

	return lengthInBits
}

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

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

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

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

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

	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

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

	return m, nil
}

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

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

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

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

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

func (m *_PublishedEventsDataType) IsPublishedEventsDataType() {}

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

func (m *_PublishedEventsDataType) deepCopy() *_PublishedEventsDataType {
	if m == nil {
		return nil
	}
	_PublishedEventsDataTypeCopy := &_PublishedEventsDataType{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[NodeId](m.EventNotifier),
		utils.DeepCopySlice[SimpleAttributeOperand, SimpleAttributeOperand](m.SelectedFields),
		utils.DeepCopy[ContentFilter](m.Filter),
	}
	_PublishedEventsDataTypeCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _PublishedEventsDataTypeCopy
}

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