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

// UpdateEventDetails is the corresponding interface of UpdateEventDetails
type UpdateEventDetails interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetNodeId returns NodeId (property field)
	GetNodeId() NodeId
	// GetPerformInsertReplace returns PerformInsertReplace (property field)
	GetPerformInsertReplace() PerformUpdateType
	// GetFilter returns Filter (property field)
	GetFilter() EventFilter
	// GetEventData returns EventData (property field)
	GetEventData() []HistoryEventFieldList
	// IsUpdateEventDetails is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsUpdateEventDetails()
	// CreateBuilder creates a UpdateEventDetailsBuilder
	CreateUpdateEventDetailsBuilder() UpdateEventDetailsBuilder
}

// _UpdateEventDetails is the data-structure of this message
type _UpdateEventDetails struct {
	ExtensionObjectDefinitionContract
	NodeId               NodeId
	PerformInsertReplace PerformUpdateType
	Filter               EventFilter
	EventData            []HistoryEventFieldList
}

var _ UpdateEventDetails = (*_UpdateEventDetails)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_UpdateEventDetails)(nil)

// NewUpdateEventDetails factory function for _UpdateEventDetails
func NewUpdateEventDetails(nodeId NodeId, performInsertReplace PerformUpdateType, filter EventFilter, eventData []HistoryEventFieldList) *_UpdateEventDetails {
	if nodeId == nil {
		panic("nodeId of type NodeId for UpdateEventDetails must not be nil")
	}
	if filter == nil {
		panic("filter of type EventFilter for UpdateEventDetails must not be nil")
	}
	_result := &_UpdateEventDetails{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		NodeId:                            nodeId,
		PerformInsertReplace:              performInsertReplace,
		Filter:                            filter,
		EventData:                         eventData,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// UpdateEventDetailsBuilder is a builder for UpdateEventDetails
type UpdateEventDetailsBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(nodeId NodeId, performInsertReplace PerformUpdateType, filter EventFilter, eventData []HistoryEventFieldList) UpdateEventDetailsBuilder
	// WithNodeId adds NodeId (property field)
	WithNodeId(NodeId) UpdateEventDetailsBuilder
	// WithNodeIdBuilder adds NodeId (property field) which is build by the builder
	WithNodeIdBuilder(func(NodeIdBuilder) NodeIdBuilder) UpdateEventDetailsBuilder
	// WithPerformInsertReplace adds PerformInsertReplace (property field)
	WithPerformInsertReplace(PerformUpdateType) UpdateEventDetailsBuilder
	// WithFilter adds Filter (property field)
	WithFilter(EventFilter) UpdateEventDetailsBuilder
	// WithFilterBuilder adds Filter (property field) which is build by the builder
	WithFilterBuilder(func(EventFilterBuilder) EventFilterBuilder) UpdateEventDetailsBuilder
	// WithEventData adds EventData (property field)
	WithEventData(...HistoryEventFieldList) UpdateEventDetailsBuilder
	// 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 UpdateEventDetails or returns an error if something is wrong
	Build() (UpdateEventDetails, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() UpdateEventDetails
}

// NewUpdateEventDetailsBuilder() creates a UpdateEventDetailsBuilder
func NewUpdateEventDetailsBuilder() UpdateEventDetailsBuilder {
	return &_UpdateEventDetailsBuilder{_UpdateEventDetails: new(_UpdateEventDetails)}
}

type _UpdateEventDetailsBuilder struct {
	*_UpdateEventDetails

	parentBuilder *_ExtensionObjectDefinitionBuilder

	err *utils.MultiError
}

var _ (UpdateEventDetailsBuilder) = (*_UpdateEventDetailsBuilder)(nil)

func (b *_UpdateEventDetailsBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._UpdateEventDetails
}

func (b *_UpdateEventDetailsBuilder) WithMandatoryFields(nodeId NodeId, performInsertReplace PerformUpdateType, filter EventFilter, eventData []HistoryEventFieldList) UpdateEventDetailsBuilder {
	return b.WithNodeId(nodeId).WithPerformInsertReplace(performInsertReplace).WithFilter(filter).WithEventData(eventData...)
}

func (b *_UpdateEventDetailsBuilder) WithNodeId(nodeId NodeId) UpdateEventDetailsBuilder {
	b.NodeId = nodeId
	return b
}

func (b *_UpdateEventDetailsBuilder) WithNodeIdBuilder(builderSupplier func(NodeIdBuilder) NodeIdBuilder) UpdateEventDetailsBuilder {
	builder := builderSupplier(b.NodeId.CreateNodeIdBuilder())
	var err error
	b.NodeId, 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, "NodeIdBuilder failed"))
	}
	return b
}

func (b *_UpdateEventDetailsBuilder) WithPerformInsertReplace(performInsertReplace PerformUpdateType) UpdateEventDetailsBuilder {
	b.PerformInsertReplace = performInsertReplace
	return b
}

func (b *_UpdateEventDetailsBuilder) WithFilter(filter EventFilter) UpdateEventDetailsBuilder {
	b.Filter = filter
	return b
}

func (b *_UpdateEventDetailsBuilder) WithFilterBuilder(builderSupplier func(EventFilterBuilder) EventFilterBuilder) UpdateEventDetailsBuilder {
	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 *_UpdateEventDetailsBuilder) WithEventData(eventData ...HistoryEventFieldList) UpdateEventDetailsBuilder {
	b.EventData = eventData
	return b
}

func (b *_UpdateEventDetailsBuilder) Build() (UpdateEventDetails, error) {
	if b.NodeId == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'nodeId' not set"))
	}
	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._UpdateEventDetails.deepCopy(), nil
}

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

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

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

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

// CreateUpdateEventDetailsBuilder creates a UpdateEventDetailsBuilder
func (b *_UpdateEventDetails) CreateUpdateEventDetailsBuilder() UpdateEventDetailsBuilder {
	if b == nil {
		return NewUpdateEventDetailsBuilder()
	}
	return &_UpdateEventDetailsBuilder{_UpdateEventDetails: b.deepCopy()}
}

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

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

func (m *_UpdateEventDetails) GetExtensionId() int32 {
	return int32(685)
}

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

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

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

func (m *_UpdateEventDetails) GetNodeId() NodeId {
	return m.NodeId
}

func (m *_UpdateEventDetails) GetPerformInsertReplace() PerformUpdateType {
	return m.PerformInsertReplace
}

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

func (m *_UpdateEventDetails) GetEventData() []HistoryEventFieldList {
	return m.EventData
}

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

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

func (m *_UpdateEventDetails) GetTypeName() string {
	return "UpdateEventDetails"
}

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

	// Simple field (nodeId)
	lengthInBits += m.NodeId.GetLengthInBits(ctx)

	// Simple field (performInsertReplace)
	lengthInBits += 32

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

	// Implicit Field (noOfEventData)
	lengthInBits += 32

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

	return lengthInBits
}

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

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

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

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

	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

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

	eventData, err := ReadCountArrayField[HistoryEventFieldList](ctx, "eventData", ReadComplex[HistoryEventFieldList](ExtensionObjectDefinitionParseWithBufferProducer[HistoryEventFieldList]((int32)(int32(922))), readBuffer), uint64(noOfEventData))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'eventData' field"))
	}
	m.EventData = eventData

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

	return m, nil
}

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

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

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

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

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

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

func (m *_UpdateEventDetails) IsUpdateEventDetails() {}

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

func (m *_UpdateEventDetails) deepCopy() *_UpdateEventDetails {
	if m == nil {
		return nil
	}
	_UpdateEventDetailsCopy := &_UpdateEventDetails{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[NodeId](m.NodeId),
		m.PerformInsertReplace,
		utils.DeepCopy[EventFilter](m.Filter),
		utils.DeepCopySlice[HistoryEventFieldList, HistoryEventFieldList](m.EventData),
	}
	_UpdateEventDetailsCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _UpdateEventDetailsCopy
}

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