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

// HistoryModifiedEvent is the corresponding interface of HistoryModifiedEvent
type HistoryModifiedEvent interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetEvents returns Events (property field)
	GetEvents() []HistoryEventFieldList
	// GetModificationInfos returns ModificationInfos (property field)
	GetModificationInfos() []ModificationInfo
	// IsHistoryModifiedEvent is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsHistoryModifiedEvent()
	// CreateBuilder creates a HistoryModifiedEventBuilder
	CreateHistoryModifiedEventBuilder() HistoryModifiedEventBuilder
}

// _HistoryModifiedEvent is the data-structure of this message
type _HistoryModifiedEvent struct {
	ExtensionObjectDefinitionContract
	Events            []HistoryEventFieldList
	ModificationInfos []ModificationInfo
}

var _ HistoryModifiedEvent = (*_HistoryModifiedEvent)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_HistoryModifiedEvent)(nil)

// NewHistoryModifiedEvent factory function for _HistoryModifiedEvent
func NewHistoryModifiedEvent(events []HistoryEventFieldList, modificationInfos []ModificationInfo) *_HistoryModifiedEvent {
	_result := &_HistoryModifiedEvent{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		Events:                            events,
		ModificationInfos:                 modificationInfos,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// HistoryModifiedEventBuilder is a builder for HistoryModifiedEvent
type HistoryModifiedEventBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(events []HistoryEventFieldList, modificationInfos []ModificationInfo) HistoryModifiedEventBuilder
	// WithEvents adds Events (property field)
	WithEvents(...HistoryEventFieldList) HistoryModifiedEventBuilder
	// WithModificationInfos adds ModificationInfos (property field)
	WithModificationInfos(...ModificationInfo) HistoryModifiedEventBuilder
	// 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 HistoryModifiedEvent or returns an error if something is wrong
	Build() (HistoryModifiedEvent, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() HistoryModifiedEvent
}

// NewHistoryModifiedEventBuilder() creates a HistoryModifiedEventBuilder
func NewHistoryModifiedEventBuilder() HistoryModifiedEventBuilder {
	return &_HistoryModifiedEventBuilder{_HistoryModifiedEvent: new(_HistoryModifiedEvent)}
}

type _HistoryModifiedEventBuilder struct {
	*_HistoryModifiedEvent

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (HistoryModifiedEventBuilder) = (*_HistoryModifiedEventBuilder)(nil)

func (b *_HistoryModifiedEventBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._HistoryModifiedEvent
}

func (b *_HistoryModifiedEventBuilder) WithMandatoryFields(events []HistoryEventFieldList, modificationInfos []ModificationInfo) HistoryModifiedEventBuilder {
	return b.WithEvents(events...).WithModificationInfos(modificationInfos...)
}

func (b *_HistoryModifiedEventBuilder) WithEvents(events ...HistoryEventFieldList) HistoryModifiedEventBuilder {
	b.Events = events
	return b
}

func (b *_HistoryModifiedEventBuilder) WithModificationInfos(modificationInfos ...ModificationInfo) HistoryModifiedEventBuilder {
	b.ModificationInfos = modificationInfos
	return b
}

func (b *_HistoryModifiedEventBuilder) Build() (HistoryModifiedEvent, error) {
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._HistoryModifiedEvent.deepCopy(), nil
}

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

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

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

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

// CreateHistoryModifiedEventBuilder creates a HistoryModifiedEventBuilder
func (b *_HistoryModifiedEvent) CreateHistoryModifiedEventBuilder() HistoryModifiedEventBuilder {
	if b == nil {
		return NewHistoryModifiedEventBuilder()
	}
	return &_HistoryModifiedEventBuilder{_HistoryModifiedEvent: b.deepCopy()}
}

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

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

func (m *_HistoryModifiedEvent) GetExtensionId() int32 {
	return int32(32826)
}

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

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

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

func (m *_HistoryModifiedEvent) GetEvents() []HistoryEventFieldList {
	return m.Events
}

func (m *_HistoryModifiedEvent) GetModificationInfos() []ModificationInfo {
	return m.ModificationInfos
}

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

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

func (m *_HistoryModifiedEvent) GetTypeName() string {
	return "HistoryModifiedEvent"
}

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

	// Implicit Field (noOfEvents)
	lengthInBits += 32

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

	// Implicit Field (noOfModificationInfos)
	lengthInBits += 32

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

	return lengthInBits
}

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

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

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

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

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

	modificationInfos, err := ReadCountArrayField[ModificationInfo](ctx, "modificationInfos", ReadComplex[ModificationInfo](ExtensionObjectDefinitionParseWithBufferProducer[ModificationInfo]((int32)(int32(11218))), readBuffer), uint64(noOfModificationInfos))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'modificationInfos' field"))
	}
	m.ModificationInfos = modificationInfos

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

	return m, nil
}

func (m *_HistoryModifiedEvent) 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 *_HistoryModifiedEvent) SerializeWithWriteBuffer(ctx context.Context, writeBuffer utils.WriteBuffer) error {
	positionAware := writeBuffer
	_ = positionAware
	log := zerolog.Ctx(ctx)
	_ = log
	ser := func() error {
		if pushErr := writeBuffer.PushContext("HistoryModifiedEvent"); pushErr != nil {
			return errors.Wrap(pushErr, "Error pushing for HistoryModifiedEvent")
		}
		noOfEvents := int32(utils.InlineIf(bool((m.GetEvents()) == (nil)), func() any { return int32(-(int32(1))) }, func() any { return int32(int32(len(m.GetEvents()))) }).(int32))
		if err := WriteImplicitField(ctx, "noOfEvents", noOfEvents, WriteSignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'noOfEvents' field")
		}

		if err := WriteComplexTypeArrayField(ctx, "events", m.GetEvents(), writeBuffer); err != nil {
			return errors.Wrap(err, "Error serializing 'events' field")
		}
		noOfModificationInfos := int32(utils.InlineIf(bool((m.GetModificationInfos()) == (nil)), func() any { return int32(-(int32(1))) }, func() any { return int32(int32(len(m.GetModificationInfos()))) }).(int32))
		if err := WriteImplicitField(ctx, "noOfModificationInfos", noOfModificationInfos, WriteSignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'noOfModificationInfos' field")
		}

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

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

func (m *_HistoryModifiedEvent) IsHistoryModifiedEvent() {}

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

func (m *_HistoryModifiedEvent) deepCopy() *_HistoryModifiedEvent {
	if m == nil {
		return nil
	}
	_HistoryModifiedEventCopy := &_HistoryModifiedEvent{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopySlice[HistoryEventFieldList, HistoryEventFieldList](m.Events),
		utils.DeepCopySlice[ModificationInfo, ModificationInfo](m.ModificationInfos),
	}
	_HistoryModifiedEventCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _HistoryModifiedEventCopy
}

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