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

// JsonPubSubConnectionMessage is the corresponding interface of JsonPubSubConnectionMessage
type JsonPubSubConnectionMessage 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
	// GetTimestamp returns Timestamp (property field)
	GetTimestamp() int64
	// GetConnection returns Connection (property field)
	GetConnection() PubSubConnectionDataType
	// IsJsonPubSubConnectionMessage is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsJsonPubSubConnectionMessage()
	// CreateBuilder creates a JsonPubSubConnectionMessageBuilder
	CreateJsonPubSubConnectionMessageBuilder() JsonPubSubConnectionMessageBuilder
}

// _JsonPubSubConnectionMessage is the data-structure of this message
type _JsonPubSubConnectionMessage struct {
	ExtensionObjectDefinitionContract
	MessageId   PascalString
	MessageType PascalString
	PublisherId PascalString
	Timestamp   int64
	Connection  PubSubConnectionDataType
}

var _ JsonPubSubConnectionMessage = (*_JsonPubSubConnectionMessage)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_JsonPubSubConnectionMessage)(nil)

// NewJsonPubSubConnectionMessage factory function for _JsonPubSubConnectionMessage
func NewJsonPubSubConnectionMessage(messageId PascalString, messageType PascalString, publisherId PascalString, timestamp int64, connection PubSubConnectionDataType) *_JsonPubSubConnectionMessage {
	if messageId == nil {
		panic("messageId of type PascalString for JsonPubSubConnectionMessage must not be nil")
	}
	if messageType == nil {
		panic("messageType of type PascalString for JsonPubSubConnectionMessage must not be nil")
	}
	if publisherId == nil {
		panic("publisherId of type PascalString for JsonPubSubConnectionMessage must not be nil")
	}
	if connection == nil {
		panic("connection of type PubSubConnectionDataType for JsonPubSubConnectionMessage must not be nil")
	}
	_result := &_JsonPubSubConnectionMessage{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		MessageId:                         messageId,
		MessageType:                       messageType,
		PublisherId:                       publisherId,
		Timestamp:                         timestamp,
		Connection:                        connection,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// JsonPubSubConnectionMessageBuilder is a builder for JsonPubSubConnectionMessage
type JsonPubSubConnectionMessageBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(messageId PascalString, messageType PascalString, publisherId PascalString, timestamp int64, connection PubSubConnectionDataType) JsonPubSubConnectionMessageBuilder
	// WithMessageId adds MessageId (property field)
	WithMessageId(PascalString) JsonPubSubConnectionMessageBuilder
	// WithMessageIdBuilder adds MessageId (property field) which is build by the builder
	WithMessageIdBuilder(func(PascalStringBuilder) PascalStringBuilder) JsonPubSubConnectionMessageBuilder
	// WithMessageType adds MessageType (property field)
	WithMessageType(PascalString) JsonPubSubConnectionMessageBuilder
	// WithMessageTypeBuilder adds MessageType (property field) which is build by the builder
	WithMessageTypeBuilder(func(PascalStringBuilder) PascalStringBuilder) JsonPubSubConnectionMessageBuilder
	// WithPublisherId adds PublisherId (property field)
	WithPublisherId(PascalString) JsonPubSubConnectionMessageBuilder
	// WithPublisherIdBuilder adds PublisherId (property field) which is build by the builder
	WithPublisherIdBuilder(func(PascalStringBuilder) PascalStringBuilder) JsonPubSubConnectionMessageBuilder
	// WithTimestamp adds Timestamp (property field)
	WithTimestamp(int64) JsonPubSubConnectionMessageBuilder
	// WithConnection adds Connection (property field)
	WithConnection(PubSubConnectionDataType) JsonPubSubConnectionMessageBuilder
	// WithConnectionBuilder adds Connection (property field) which is build by the builder
	WithConnectionBuilder(func(PubSubConnectionDataTypeBuilder) PubSubConnectionDataTypeBuilder) JsonPubSubConnectionMessageBuilder
	// 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 JsonPubSubConnectionMessage or returns an error if something is wrong
	Build() (JsonPubSubConnectionMessage, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() JsonPubSubConnectionMessage
}

// NewJsonPubSubConnectionMessageBuilder() creates a JsonPubSubConnectionMessageBuilder
func NewJsonPubSubConnectionMessageBuilder() JsonPubSubConnectionMessageBuilder {
	return &_JsonPubSubConnectionMessageBuilder{_JsonPubSubConnectionMessage: new(_JsonPubSubConnectionMessage)}
}

type _JsonPubSubConnectionMessageBuilder struct {
	*_JsonPubSubConnectionMessage

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (JsonPubSubConnectionMessageBuilder) = (*_JsonPubSubConnectionMessageBuilder)(nil)

func (b *_JsonPubSubConnectionMessageBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._JsonPubSubConnectionMessage
}

func (b *_JsonPubSubConnectionMessageBuilder) WithMandatoryFields(messageId PascalString, messageType PascalString, publisherId PascalString, timestamp int64, connection PubSubConnectionDataType) JsonPubSubConnectionMessageBuilder {
	return b.WithMessageId(messageId).WithMessageType(messageType).WithPublisherId(publisherId).WithTimestamp(timestamp).WithConnection(connection)
}

func (b *_JsonPubSubConnectionMessageBuilder) WithMessageId(messageId PascalString) JsonPubSubConnectionMessageBuilder {
	b.MessageId = messageId
	return b
}

func (b *_JsonPubSubConnectionMessageBuilder) WithMessageIdBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) JsonPubSubConnectionMessageBuilder {
	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 *_JsonPubSubConnectionMessageBuilder) WithMessageType(messageType PascalString) JsonPubSubConnectionMessageBuilder {
	b.MessageType = messageType
	return b
}

func (b *_JsonPubSubConnectionMessageBuilder) WithMessageTypeBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) JsonPubSubConnectionMessageBuilder {
	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 *_JsonPubSubConnectionMessageBuilder) WithPublisherId(publisherId PascalString) JsonPubSubConnectionMessageBuilder {
	b.PublisherId = publisherId
	return b
}

func (b *_JsonPubSubConnectionMessageBuilder) WithPublisherIdBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) JsonPubSubConnectionMessageBuilder {
	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 *_JsonPubSubConnectionMessageBuilder) WithTimestamp(timestamp int64) JsonPubSubConnectionMessageBuilder {
	b.Timestamp = timestamp
	return b
}

func (b *_JsonPubSubConnectionMessageBuilder) WithConnection(connection PubSubConnectionDataType) JsonPubSubConnectionMessageBuilder {
	b.Connection = connection
	return b
}

func (b *_JsonPubSubConnectionMessageBuilder) WithConnectionBuilder(builderSupplier func(PubSubConnectionDataTypeBuilder) PubSubConnectionDataTypeBuilder) JsonPubSubConnectionMessageBuilder {
	builder := builderSupplier(b.Connection.CreatePubSubConnectionDataTypeBuilder())
	var err error
	b.Connection, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "PubSubConnectionDataTypeBuilder failed"))
	}
	return b
}

func (b *_JsonPubSubConnectionMessageBuilder) Build() (JsonPubSubConnectionMessage, 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.Connection == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'connection' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._JsonPubSubConnectionMessage.deepCopy(), nil
}

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

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

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

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

// CreateJsonPubSubConnectionMessageBuilder creates a JsonPubSubConnectionMessageBuilder
func (b *_JsonPubSubConnectionMessage) CreateJsonPubSubConnectionMessageBuilder() JsonPubSubConnectionMessageBuilder {
	if b == nil {
		return NewJsonPubSubConnectionMessageBuilder()
	}
	return &_JsonPubSubConnectionMessageBuilder{_JsonPubSubConnectionMessage: b.deepCopy()}
}

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

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

func (m *_JsonPubSubConnectionMessage) GetExtensionId() int32 {
	return int32(19319)
}

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

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

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

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

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

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

func (m *_JsonPubSubConnectionMessage) GetTimestamp() int64 {
	return m.Timestamp
}

func (m *_JsonPubSubConnectionMessage) GetConnection() PubSubConnectionDataType {
	return m.Connection
}

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

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

func (m *_JsonPubSubConnectionMessage) GetTypeName() string {
	return "JsonPubSubConnectionMessage"
}

func (m *_JsonPubSubConnectionMessage) 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 (timestamp)
	lengthInBits += 64

	// Simple field (connection)
	lengthInBits += m.Connection.GetLengthInBits(ctx)

	return lengthInBits
}

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

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

	timestamp, err := ReadSimpleField(ctx, "timestamp", ReadSignedLong(readBuffer, uint8(64)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'timestamp' field"))
	}
	m.Timestamp = timestamp

	connection, err := ReadSimpleField[PubSubConnectionDataType](ctx, "connection", ReadComplex[PubSubConnectionDataType](ExtensionObjectDefinitionParseWithBufferProducer[PubSubConnectionDataType]((int32)(int32(15619))), readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'connection' field"))
	}
	m.Connection = connection

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

	return m, nil
}

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

		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[int64](ctx, "timestamp", m.GetTimestamp(), WriteSignedLong(writeBuffer, 64)); err != nil {
			return errors.Wrap(err, "Error serializing 'timestamp' field")
		}

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

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

func (m *_JsonPubSubConnectionMessage) IsJsonPubSubConnectionMessage() {}

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

func (m *_JsonPubSubConnectionMessage) deepCopy() *_JsonPubSubConnectionMessage {
	if m == nil {
		return nil
	}
	_JsonPubSubConnectionMessageCopy := &_JsonPubSubConnectionMessage{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[PascalString](m.MessageId),
		utils.DeepCopy[PascalString](m.MessageType),
		utils.DeepCopy[PascalString](m.PublisherId),
		m.Timestamp,
		utils.DeepCopy[PubSubConnectionDataType](m.Connection),
	}
	_JsonPubSubConnectionMessageCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _JsonPubSubConnectionMessageCopy
}

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