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

// JsonServerEndpointsMessage is the corresponding interface of JsonServerEndpointsMessage
type JsonServerEndpointsMessage 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
	// GetDescription returns Description (property field)
	GetDescription() ApplicationDescription
	// GetEndpoints returns Endpoints (property field)
	GetEndpoints() []EndpointDescription
	// IsJsonServerEndpointsMessage is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsJsonServerEndpointsMessage()
	// CreateBuilder creates a JsonServerEndpointsMessageBuilder
	CreateJsonServerEndpointsMessageBuilder() JsonServerEndpointsMessageBuilder
}

// _JsonServerEndpointsMessage is the data-structure of this message
type _JsonServerEndpointsMessage struct {
	ExtensionObjectDefinitionContract
	MessageId   PascalString
	MessageType PascalString
	PublisherId PascalString
	Timestamp   int64
	Description ApplicationDescription
	Endpoints   []EndpointDescription
}

var _ JsonServerEndpointsMessage = (*_JsonServerEndpointsMessage)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_JsonServerEndpointsMessage)(nil)

// NewJsonServerEndpointsMessage factory function for _JsonServerEndpointsMessage
func NewJsonServerEndpointsMessage(messageId PascalString, messageType PascalString, publisherId PascalString, timestamp int64, description ApplicationDescription, endpoints []EndpointDescription) *_JsonServerEndpointsMessage {
	if messageId == nil {
		panic("messageId of type PascalString for JsonServerEndpointsMessage must not be nil")
	}
	if messageType == nil {
		panic("messageType of type PascalString for JsonServerEndpointsMessage must not be nil")
	}
	if publisherId == nil {
		panic("publisherId of type PascalString for JsonServerEndpointsMessage must not be nil")
	}
	if description == nil {
		panic("description of type ApplicationDescription for JsonServerEndpointsMessage must not be nil")
	}
	_result := &_JsonServerEndpointsMessage{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		MessageId:                         messageId,
		MessageType:                       messageType,
		PublisherId:                       publisherId,
		Timestamp:                         timestamp,
		Description:                       description,
		Endpoints:                         endpoints,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// JsonServerEndpointsMessageBuilder is a builder for JsonServerEndpointsMessage
type JsonServerEndpointsMessageBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(messageId PascalString, messageType PascalString, publisherId PascalString, timestamp int64, description ApplicationDescription, endpoints []EndpointDescription) JsonServerEndpointsMessageBuilder
	// WithMessageId adds MessageId (property field)
	WithMessageId(PascalString) JsonServerEndpointsMessageBuilder
	// WithMessageIdBuilder adds MessageId (property field) which is build by the builder
	WithMessageIdBuilder(func(PascalStringBuilder) PascalStringBuilder) JsonServerEndpointsMessageBuilder
	// WithMessageType adds MessageType (property field)
	WithMessageType(PascalString) JsonServerEndpointsMessageBuilder
	// WithMessageTypeBuilder adds MessageType (property field) which is build by the builder
	WithMessageTypeBuilder(func(PascalStringBuilder) PascalStringBuilder) JsonServerEndpointsMessageBuilder
	// WithPublisherId adds PublisherId (property field)
	WithPublisherId(PascalString) JsonServerEndpointsMessageBuilder
	// WithPublisherIdBuilder adds PublisherId (property field) which is build by the builder
	WithPublisherIdBuilder(func(PascalStringBuilder) PascalStringBuilder) JsonServerEndpointsMessageBuilder
	// WithTimestamp adds Timestamp (property field)
	WithTimestamp(int64) JsonServerEndpointsMessageBuilder
	// WithDescription adds Description (property field)
	WithDescription(ApplicationDescription) JsonServerEndpointsMessageBuilder
	// WithDescriptionBuilder adds Description (property field) which is build by the builder
	WithDescriptionBuilder(func(ApplicationDescriptionBuilder) ApplicationDescriptionBuilder) JsonServerEndpointsMessageBuilder
	// WithEndpoints adds Endpoints (property field)
	WithEndpoints(...EndpointDescription) JsonServerEndpointsMessageBuilder
	// 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 JsonServerEndpointsMessage or returns an error if something is wrong
	Build() (JsonServerEndpointsMessage, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() JsonServerEndpointsMessage
}

// NewJsonServerEndpointsMessageBuilder() creates a JsonServerEndpointsMessageBuilder
func NewJsonServerEndpointsMessageBuilder() JsonServerEndpointsMessageBuilder {
	return &_JsonServerEndpointsMessageBuilder{_JsonServerEndpointsMessage: new(_JsonServerEndpointsMessage)}
}

type _JsonServerEndpointsMessageBuilder struct {
	*_JsonServerEndpointsMessage

	parentBuilder *_ExtensionObjectDefinitionBuilder

	err *utils.MultiError
}

var _ (JsonServerEndpointsMessageBuilder) = (*_JsonServerEndpointsMessageBuilder)(nil)

func (b *_JsonServerEndpointsMessageBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._JsonServerEndpointsMessage
}

func (b *_JsonServerEndpointsMessageBuilder) WithMandatoryFields(messageId PascalString, messageType PascalString, publisherId PascalString, timestamp int64, description ApplicationDescription, endpoints []EndpointDescription) JsonServerEndpointsMessageBuilder {
	return b.WithMessageId(messageId).WithMessageType(messageType).WithPublisherId(publisherId).WithTimestamp(timestamp).WithDescription(description).WithEndpoints(endpoints...)
}

func (b *_JsonServerEndpointsMessageBuilder) WithMessageId(messageId PascalString) JsonServerEndpointsMessageBuilder {
	b.MessageId = messageId
	return b
}

func (b *_JsonServerEndpointsMessageBuilder) WithMessageIdBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) JsonServerEndpointsMessageBuilder {
	builder := builderSupplier(b.MessageId.CreatePascalStringBuilder())
	var err error
	b.MessageId, 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, "PascalStringBuilder failed"))
	}
	return b
}

func (b *_JsonServerEndpointsMessageBuilder) WithMessageType(messageType PascalString) JsonServerEndpointsMessageBuilder {
	b.MessageType = messageType
	return b
}

func (b *_JsonServerEndpointsMessageBuilder) WithMessageTypeBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) JsonServerEndpointsMessageBuilder {
	builder := builderSupplier(b.MessageType.CreatePascalStringBuilder())
	var err error
	b.MessageType, 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, "PascalStringBuilder failed"))
	}
	return b
}

func (b *_JsonServerEndpointsMessageBuilder) WithPublisherId(publisherId PascalString) JsonServerEndpointsMessageBuilder {
	b.PublisherId = publisherId
	return b
}

func (b *_JsonServerEndpointsMessageBuilder) WithPublisherIdBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) JsonServerEndpointsMessageBuilder {
	builder := builderSupplier(b.PublisherId.CreatePascalStringBuilder())
	var err error
	b.PublisherId, 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, "PascalStringBuilder failed"))
	}
	return b
}

func (b *_JsonServerEndpointsMessageBuilder) WithTimestamp(timestamp int64) JsonServerEndpointsMessageBuilder {
	b.Timestamp = timestamp
	return b
}

func (b *_JsonServerEndpointsMessageBuilder) WithDescription(description ApplicationDescription) JsonServerEndpointsMessageBuilder {
	b.Description = description
	return b
}

func (b *_JsonServerEndpointsMessageBuilder) WithDescriptionBuilder(builderSupplier func(ApplicationDescriptionBuilder) ApplicationDescriptionBuilder) JsonServerEndpointsMessageBuilder {
	builder := builderSupplier(b.Description.CreateApplicationDescriptionBuilder())
	var err error
	b.Description, 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, "ApplicationDescriptionBuilder failed"))
	}
	return b
}

func (b *_JsonServerEndpointsMessageBuilder) WithEndpoints(endpoints ...EndpointDescription) JsonServerEndpointsMessageBuilder {
	b.Endpoints = endpoints
	return b
}

func (b *_JsonServerEndpointsMessageBuilder) Build() (JsonServerEndpointsMessage, error) {
	if b.MessageId == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'messageId' not set"))
	}
	if b.MessageType == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'messageType' not set"))
	}
	if b.PublisherId == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'publisherId' not set"))
	}
	if b.Description == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'description' not set"))
	}
	if b.err != nil {
		return nil, errors.Wrap(b.err, "error occurred during build")
	}
	return b._JsonServerEndpointsMessage.deepCopy(), nil
}

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

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

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

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

// CreateJsonServerEndpointsMessageBuilder creates a JsonServerEndpointsMessageBuilder
func (b *_JsonServerEndpointsMessage) CreateJsonServerEndpointsMessageBuilder() JsonServerEndpointsMessageBuilder {
	if b == nil {
		return NewJsonServerEndpointsMessageBuilder()
	}
	return &_JsonServerEndpointsMessageBuilder{_JsonServerEndpointsMessage: b.deepCopy()}
}

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

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

func (m *_JsonServerEndpointsMessage) GetExtensionId() int32 {
	return int32(19317)
}

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

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

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

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

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

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

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

func (m *_JsonServerEndpointsMessage) GetDescription() ApplicationDescription {
	return m.Description
}

func (m *_JsonServerEndpointsMessage) GetEndpoints() []EndpointDescription {
	return m.Endpoints
}

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

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

func (m *_JsonServerEndpointsMessage) GetTypeName() string {
	return "JsonServerEndpointsMessage"
}

func (m *_JsonServerEndpointsMessage) 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 (description)
	lengthInBits += m.Description.GetLengthInBits(ctx)

	// Implicit Field (noOfEndpoints)
	lengthInBits += 32

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

	return lengthInBits
}

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

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

	description, err := ReadSimpleField[ApplicationDescription](ctx, "description", ReadComplex[ApplicationDescription](ExtensionObjectDefinitionParseWithBufferProducer[ApplicationDescription]((int32)(int32(310))), readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'description' field"))
	}
	m.Description = description

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

	endpoints, err := ReadCountArrayField[EndpointDescription](ctx, "endpoints", ReadComplex[EndpointDescription](ExtensionObjectDefinitionParseWithBufferProducer[EndpointDescription]((int32)(int32(314))), readBuffer), uint64(noOfEndpoints))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'endpoints' field"))
	}
	m.Endpoints = endpoints

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

	return m, nil
}

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

		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[ApplicationDescription](ctx, "description", m.GetDescription(), WriteComplex[ApplicationDescription](writeBuffer)); err != nil {
			return errors.Wrap(err, "Error serializing 'description' field")
		}
		noOfEndpoints := int32(utils.InlineIf(bool((m.GetEndpoints()) == (nil)), func() any { return int32(-(int32(1))) }, func() any { return int32(int32(len(m.GetEndpoints()))) }).(int32))
		if err := WriteImplicitField(ctx, "noOfEndpoints", noOfEndpoints, WriteSignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'noOfEndpoints' field")
		}

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

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

func (m *_JsonServerEndpointsMessage) IsJsonServerEndpointsMessage() {}

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

func (m *_JsonServerEndpointsMessage) deepCopy() *_JsonServerEndpointsMessage {
	if m == nil {
		return nil
	}
	_JsonServerEndpointsMessageCopy := &_JsonServerEndpointsMessage{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[PascalString](m.MessageId),
		utils.DeepCopy[PascalString](m.MessageType),
		utils.DeepCopy[PascalString](m.PublisherId),
		m.Timestamp,
		utils.DeepCopy[ApplicationDescription](m.Description),
		utils.DeepCopySlice[EndpointDescription, EndpointDescription](m.Endpoints),
	}
	_JsonServerEndpointsMessageCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _JsonServerEndpointsMessageCopy
}

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