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

// JsonNetworkMessage is the corresponding interface of JsonNetworkMessage
type JsonNetworkMessage interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetMessageId returns MessageId (property field)
	GetMessageId() PascalString
	// GetMessageType returns MessageType (property field)
	GetMessageType() PascalString
	// GetPublisherId returns PublisherId (property field)
	GetPublisherId() PascalString
	// GetWriterGroupName returns WriterGroupName (property field)
	GetWriterGroupName() PascalString
	// GetDataSetClassId returns DataSetClassId (property field)
	GetDataSetClassId() PascalString
	// GetMessages returns Messages (property field)
	GetMessages() []ExtensionObject
	// IsJsonNetworkMessage is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsJsonNetworkMessage()
	// CreateBuilder creates a JsonNetworkMessageBuilder
	CreateJsonNetworkMessageBuilder() JsonNetworkMessageBuilder
}

// _JsonNetworkMessage is the data-structure of this message
type _JsonNetworkMessage struct {
	ExtensionObjectDefinitionContract
	MessageId       PascalString
	MessageType     PascalString
	PublisherId     PascalString
	WriterGroupName PascalString
	DataSetClassId  PascalString
	Messages        []ExtensionObject
}

var _ JsonNetworkMessage = (*_JsonNetworkMessage)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_JsonNetworkMessage)(nil)

// NewJsonNetworkMessage factory function for _JsonNetworkMessage
func NewJsonNetworkMessage(messageId PascalString, messageType PascalString, publisherId PascalString, writerGroupName PascalString, dataSetClassId PascalString, messages []ExtensionObject) *_JsonNetworkMessage {
	if messageId == nil {
		panic("messageId of type PascalString for JsonNetworkMessage must not be nil")
	}
	if messageType == nil {
		panic("messageType of type PascalString for JsonNetworkMessage must not be nil")
	}
	if publisherId == nil {
		panic("publisherId of type PascalString for JsonNetworkMessage must not be nil")
	}
	if writerGroupName == nil {
		panic("writerGroupName of type PascalString for JsonNetworkMessage must not be nil")
	}
	if dataSetClassId == nil {
		panic("dataSetClassId of type PascalString for JsonNetworkMessage must not be nil")
	}
	_result := &_JsonNetworkMessage{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		MessageId:                         messageId,
		MessageType:                       messageType,
		PublisherId:                       publisherId,
		WriterGroupName:                   writerGroupName,
		DataSetClassId:                    dataSetClassId,
		Messages:                          messages,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// JsonNetworkMessageBuilder is a builder for JsonNetworkMessage
type JsonNetworkMessageBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(messageId PascalString, messageType PascalString, publisherId PascalString, writerGroupName PascalString, dataSetClassId PascalString, messages []ExtensionObject) JsonNetworkMessageBuilder
	// WithMessageId adds MessageId (property field)
	WithMessageId(PascalString) JsonNetworkMessageBuilder
	// WithMessageIdBuilder adds MessageId (property field) which is build by the builder
	WithMessageIdBuilder(func(PascalStringBuilder) PascalStringBuilder) JsonNetworkMessageBuilder
	// WithMessageType adds MessageType (property field)
	WithMessageType(PascalString) JsonNetworkMessageBuilder
	// WithMessageTypeBuilder adds MessageType (property field) which is build by the builder
	WithMessageTypeBuilder(func(PascalStringBuilder) PascalStringBuilder) JsonNetworkMessageBuilder
	// WithPublisherId adds PublisherId (property field)
	WithPublisherId(PascalString) JsonNetworkMessageBuilder
	// WithPublisherIdBuilder adds PublisherId (property field) which is build by the builder
	WithPublisherIdBuilder(func(PascalStringBuilder) PascalStringBuilder) JsonNetworkMessageBuilder
	// WithWriterGroupName adds WriterGroupName (property field)
	WithWriterGroupName(PascalString) JsonNetworkMessageBuilder
	// WithWriterGroupNameBuilder adds WriterGroupName (property field) which is build by the builder
	WithWriterGroupNameBuilder(func(PascalStringBuilder) PascalStringBuilder) JsonNetworkMessageBuilder
	// WithDataSetClassId adds DataSetClassId (property field)
	WithDataSetClassId(PascalString) JsonNetworkMessageBuilder
	// WithDataSetClassIdBuilder adds DataSetClassId (property field) which is build by the builder
	WithDataSetClassIdBuilder(func(PascalStringBuilder) PascalStringBuilder) JsonNetworkMessageBuilder
	// WithMessages adds Messages (property field)
	WithMessages(...ExtensionObject) JsonNetworkMessageBuilder
	// 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 JsonNetworkMessage or returns an error if something is wrong
	Build() (JsonNetworkMessage, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() JsonNetworkMessage
}

// NewJsonNetworkMessageBuilder() creates a JsonNetworkMessageBuilder
func NewJsonNetworkMessageBuilder() JsonNetworkMessageBuilder {
	return &_JsonNetworkMessageBuilder{_JsonNetworkMessage: new(_JsonNetworkMessage)}
}

type _JsonNetworkMessageBuilder struct {
	*_JsonNetworkMessage

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (JsonNetworkMessageBuilder) = (*_JsonNetworkMessageBuilder)(nil)

func (b *_JsonNetworkMessageBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._JsonNetworkMessage
}

func (b *_JsonNetworkMessageBuilder) WithMandatoryFields(messageId PascalString, messageType PascalString, publisherId PascalString, writerGroupName PascalString, dataSetClassId PascalString, messages []ExtensionObject) JsonNetworkMessageBuilder {
	return b.WithMessageId(messageId).WithMessageType(messageType).WithPublisherId(publisherId).WithWriterGroupName(writerGroupName).WithDataSetClassId(dataSetClassId).WithMessages(messages...)
}

func (b *_JsonNetworkMessageBuilder) WithMessageId(messageId PascalString) JsonNetworkMessageBuilder {
	b.MessageId = messageId
	return b
}

func (b *_JsonNetworkMessageBuilder) WithMessageIdBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) JsonNetworkMessageBuilder {
	builder := builderSupplier(b.MessageId.CreatePascalStringBuilder())
	var err error
	b.MessageId, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "PascalStringBuilder failed"))
	}
	return b
}

func (b *_JsonNetworkMessageBuilder) WithMessageType(messageType PascalString) JsonNetworkMessageBuilder {
	b.MessageType = messageType
	return b
}

func (b *_JsonNetworkMessageBuilder) WithMessageTypeBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) JsonNetworkMessageBuilder {
	builder := builderSupplier(b.MessageType.CreatePascalStringBuilder())
	var err error
	b.MessageType, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "PascalStringBuilder failed"))
	}
	return b
}

func (b *_JsonNetworkMessageBuilder) WithPublisherId(publisherId PascalString) JsonNetworkMessageBuilder {
	b.PublisherId = publisherId
	return b
}

func (b *_JsonNetworkMessageBuilder) WithPublisherIdBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) JsonNetworkMessageBuilder {
	builder := builderSupplier(b.PublisherId.CreatePascalStringBuilder())
	var err error
	b.PublisherId, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "PascalStringBuilder failed"))
	}
	return b
}

func (b *_JsonNetworkMessageBuilder) WithWriterGroupName(writerGroupName PascalString) JsonNetworkMessageBuilder {
	b.WriterGroupName = writerGroupName
	return b
}

func (b *_JsonNetworkMessageBuilder) WithWriterGroupNameBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) JsonNetworkMessageBuilder {
	builder := builderSupplier(b.WriterGroupName.CreatePascalStringBuilder())
	var err error
	b.WriterGroupName, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "PascalStringBuilder failed"))
	}
	return b
}

func (b *_JsonNetworkMessageBuilder) WithDataSetClassId(dataSetClassId PascalString) JsonNetworkMessageBuilder {
	b.DataSetClassId = dataSetClassId
	return b
}

func (b *_JsonNetworkMessageBuilder) WithDataSetClassIdBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) JsonNetworkMessageBuilder {
	builder := builderSupplier(b.DataSetClassId.CreatePascalStringBuilder())
	var err error
	b.DataSetClassId, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "PascalStringBuilder failed"))
	}
	return b
}

func (b *_JsonNetworkMessageBuilder) WithMessages(messages ...ExtensionObject) JsonNetworkMessageBuilder {
	b.Messages = messages
	return b
}

func (b *_JsonNetworkMessageBuilder) Build() (JsonNetworkMessage, error) {
	if b.MessageId == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'messageId' not set"))
	}
	if b.MessageType == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'messageType' not set"))
	}
	if b.PublisherId == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'publisherId' not set"))
	}
	if b.WriterGroupName == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'writerGroupName' not set"))
	}
	if b.DataSetClassId == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'dataSetClassId' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._JsonNetworkMessage.deepCopy(), nil
}

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

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

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

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

// CreateJsonNetworkMessageBuilder creates a JsonNetworkMessageBuilder
func (b *_JsonNetworkMessage) CreateJsonNetworkMessageBuilder() JsonNetworkMessageBuilder {
	if b == nil {
		return NewJsonNetworkMessageBuilder()
	}
	return &_JsonNetworkMessageBuilder{_JsonNetworkMessage: b.deepCopy()}
}

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

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

func (m *_JsonNetworkMessage) GetExtensionId() int32 {
	return int32(19313)
}

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

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

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

func (m *_JsonNetworkMessage) GetMessageId() PascalString {
	return m.MessageId
}

func (m *_JsonNetworkMessage) GetMessageType() PascalString {
	return m.MessageType
}

func (m *_JsonNetworkMessage) GetPublisherId() PascalString {
	return m.PublisherId
}

func (m *_JsonNetworkMessage) GetWriterGroupName() PascalString {
	return m.WriterGroupName
}

func (m *_JsonNetworkMessage) GetDataSetClassId() PascalString {
	return m.DataSetClassId
}

func (m *_JsonNetworkMessage) GetMessages() []ExtensionObject {
	return m.Messages
}

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

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

func (m *_JsonNetworkMessage) GetTypeName() string {
	return "JsonNetworkMessage"
}

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

	// Simple field (messageId)
	lengthInBits += m.MessageId.GetLengthInBits(ctx)

	// Simple field (messageType)
	lengthInBits += m.MessageType.GetLengthInBits(ctx)

	// Simple field (publisherId)
	lengthInBits += m.PublisherId.GetLengthInBits(ctx)

	// Simple field (writerGroupName)
	lengthInBits += m.WriterGroupName.GetLengthInBits(ctx)

	// Simple field (dataSetClassId)
	lengthInBits += m.DataSetClassId.GetLengthInBits(ctx)

	// Implicit Field (noOfMessages)
	lengthInBits += 32

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

	return lengthInBits
}

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

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

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

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

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

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

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

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

	messages, err := ReadCountArrayField[ExtensionObject](ctx, "messages", ReadComplex[ExtensionObject](ExtensionObjectParseWithBufferProducer[ExtensionObject]((bool)(bool(true))), readBuffer), uint64(noOfMessages))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'messages' field"))
	}
	m.Messages = messages

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

	return m, nil
}

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

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

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

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

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

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

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

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

func (m *_JsonNetworkMessage) IsJsonNetworkMessage() {}

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

func (m *_JsonNetworkMessage) deepCopy() *_JsonNetworkMessage {
	if m == nil {
		return nil
	}
	_JsonNetworkMessageCopy := &_JsonNetworkMessage{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[PascalString](m.MessageId),
		utils.DeepCopy[PascalString](m.MessageType),
		utils.DeepCopy[PascalString](m.PublisherId),
		utils.DeepCopy[PascalString](m.WriterGroupName),
		utils.DeepCopy[PascalString](m.DataSetClassId),
		utils.DeepCopySlice[ExtensionObject, ExtensionObject](m.Messages),
	}
	_JsonNetworkMessageCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _JsonNetworkMessageCopy
}

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