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

// DeleteEventDetails is the corresponding interface of DeleteEventDetails
type DeleteEventDetails interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetNodeId returns NodeId (property field)
	GetNodeId() NodeId
	// GetEventIds returns EventIds (property field)
	GetEventIds() []PascalByteString
	// IsDeleteEventDetails is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsDeleteEventDetails()
	// CreateBuilder creates a DeleteEventDetailsBuilder
	CreateDeleteEventDetailsBuilder() DeleteEventDetailsBuilder
}

// _DeleteEventDetails is the data-structure of this message
type _DeleteEventDetails struct {
	ExtensionObjectDefinitionContract
	NodeId   NodeId
	EventIds []PascalByteString
}

var _ DeleteEventDetails = (*_DeleteEventDetails)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_DeleteEventDetails)(nil)

// NewDeleteEventDetails factory function for _DeleteEventDetails
func NewDeleteEventDetails(nodeId NodeId, eventIds []PascalByteString) *_DeleteEventDetails {
	if nodeId == nil {
		panic("nodeId of type NodeId for DeleteEventDetails must not be nil")
	}
	_result := &_DeleteEventDetails{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		NodeId:                            nodeId,
		EventIds:                          eventIds,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// DeleteEventDetailsBuilder is a builder for DeleteEventDetails
type DeleteEventDetailsBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(nodeId NodeId, eventIds []PascalByteString) DeleteEventDetailsBuilder
	// WithNodeId adds NodeId (property field)
	WithNodeId(NodeId) DeleteEventDetailsBuilder
	// WithNodeIdBuilder adds NodeId (property field) which is build by the builder
	WithNodeIdBuilder(func(NodeIdBuilder) NodeIdBuilder) DeleteEventDetailsBuilder
	// WithEventIds adds EventIds (property field)
	WithEventIds(...PascalByteString) DeleteEventDetailsBuilder
	// 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 DeleteEventDetails or returns an error if something is wrong
	Build() (DeleteEventDetails, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() DeleteEventDetails
}

// NewDeleteEventDetailsBuilder() creates a DeleteEventDetailsBuilder
func NewDeleteEventDetailsBuilder() DeleteEventDetailsBuilder {
	return &_DeleteEventDetailsBuilder{_DeleteEventDetails: new(_DeleteEventDetails)}
}

type _DeleteEventDetailsBuilder struct {
	*_DeleteEventDetails

	parentBuilder *_ExtensionObjectDefinitionBuilder

	err *utils.MultiError
}

var _ (DeleteEventDetailsBuilder) = (*_DeleteEventDetailsBuilder)(nil)

func (b *_DeleteEventDetailsBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._DeleteEventDetails
}

func (b *_DeleteEventDetailsBuilder) WithMandatoryFields(nodeId NodeId, eventIds []PascalByteString) DeleteEventDetailsBuilder {
	return b.WithNodeId(nodeId).WithEventIds(eventIds...)
}

func (b *_DeleteEventDetailsBuilder) WithNodeId(nodeId NodeId) DeleteEventDetailsBuilder {
	b.NodeId = nodeId
	return b
}

func (b *_DeleteEventDetailsBuilder) WithNodeIdBuilder(builderSupplier func(NodeIdBuilder) NodeIdBuilder) DeleteEventDetailsBuilder {
	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 *_DeleteEventDetailsBuilder) WithEventIds(eventIds ...PascalByteString) DeleteEventDetailsBuilder {
	b.EventIds = eventIds
	return b
}

func (b *_DeleteEventDetailsBuilder) Build() (DeleteEventDetails, 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.err != nil {
		return nil, errors.Wrap(b.err, "error occurred during build")
	}
	return b._DeleteEventDetails.deepCopy(), nil
}

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

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

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

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

// CreateDeleteEventDetailsBuilder creates a DeleteEventDetailsBuilder
func (b *_DeleteEventDetails) CreateDeleteEventDetailsBuilder() DeleteEventDetailsBuilder {
	if b == nil {
		return NewDeleteEventDetailsBuilder()
	}
	return &_DeleteEventDetailsBuilder{_DeleteEventDetails: b.deepCopy()}
}

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

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

func (m *_DeleteEventDetails) GetExtensionId() int32 {
	return int32(694)
}

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

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

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

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

func (m *_DeleteEventDetails) GetEventIds() []PascalByteString {
	return m.EventIds
}

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

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

func (m *_DeleteEventDetails) GetTypeName() string {
	return "DeleteEventDetails"
}

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

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

	// Implicit Field (noOfEventIds)
	lengthInBits += 32

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

	return lengthInBits
}

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

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

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

	eventIds, err := ReadCountArrayField[PascalByteString](ctx, "eventIds", ReadComplex[PascalByteString](PascalByteStringParseWithBuffer, readBuffer), uint64(noOfEventIds))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'eventIds' field"))
	}
	m.EventIds = eventIds

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

	return m, nil
}

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

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

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

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

func (m *_DeleteEventDetails) IsDeleteEventDetails() {}

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

func (m *_DeleteEventDetails) deepCopy() *_DeleteEventDetails {
	if m == nil {
		return nil
	}
	_DeleteEventDetailsCopy := &_DeleteEventDetails{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[NodeId](m.NodeId),
		utils.DeepCopySlice[PascalByteString, PascalByteString](m.EventIds),
	}
	_DeleteEventDetailsCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _DeleteEventDetailsCopy
}

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