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

// EndpointDataType is the corresponding interface of EndpointDataType
type EndpointDataType interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetName returns Name (property field)
	GetName() PascalString
	// GetRecordProperties returns RecordProperties (property field)
	GetRecordProperties() []KeyValuePair
	// GetDiscoveryUrls returns DiscoveryUrls (property field)
	GetDiscoveryUrls() []PascalString
	// GetNetworkName returns NetworkName (property field)
	GetNetworkName() PascalString
	// GetPort returns Port (property field)
	GetPort() uint16
	// IsEndpointDataType is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsEndpointDataType()
	// CreateBuilder creates a EndpointDataTypeBuilder
	CreateEndpointDataTypeBuilder() EndpointDataTypeBuilder
}

// _EndpointDataType is the data-structure of this message
type _EndpointDataType struct {
	ExtensionObjectDefinitionContract
	Name             PascalString
	RecordProperties []KeyValuePair
	DiscoveryUrls    []PascalString
	NetworkName      PascalString
	Port             uint16
}

var _ EndpointDataType = (*_EndpointDataType)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_EndpointDataType)(nil)

// NewEndpointDataType factory function for _EndpointDataType
func NewEndpointDataType(name PascalString, recordProperties []KeyValuePair, discoveryUrls []PascalString, networkName PascalString, port uint16) *_EndpointDataType {
	if name == nil {
		panic("name of type PascalString for EndpointDataType must not be nil")
	}
	if networkName == nil {
		panic("networkName of type PascalString for EndpointDataType must not be nil")
	}
	_result := &_EndpointDataType{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		Name:                              name,
		RecordProperties:                  recordProperties,
		DiscoveryUrls:                     discoveryUrls,
		NetworkName:                       networkName,
		Port:                              port,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// EndpointDataTypeBuilder is a builder for EndpointDataType
type EndpointDataTypeBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(name PascalString, recordProperties []KeyValuePair, discoveryUrls []PascalString, networkName PascalString, port uint16) EndpointDataTypeBuilder
	// WithName adds Name (property field)
	WithName(PascalString) EndpointDataTypeBuilder
	// WithNameBuilder adds Name (property field) which is build by the builder
	WithNameBuilder(func(PascalStringBuilder) PascalStringBuilder) EndpointDataTypeBuilder
	// WithRecordProperties adds RecordProperties (property field)
	WithRecordProperties(...KeyValuePair) EndpointDataTypeBuilder
	// WithDiscoveryUrls adds DiscoveryUrls (property field)
	WithDiscoveryUrls(...PascalString) EndpointDataTypeBuilder
	// WithNetworkName adds NetworkName (property field)
	WithNetworkName(PascalString) EndpointDataTypeBuilder
	// WithNetworkNameBuilder adds NetworkName (property field) which is build by the builder
	WithNetworkNameBuilder(func(PascalStringBuilder) PascalStringBuilder) EndpointDataTypeBuilder
	// WithPort adds Port (property field)
	WithPort(uint16) EndpointDataTypeBuilder
	// 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 EndpointDataType or returns an error if something is wrong
	Build() (EndpointDataType, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() EndpointDataType
}

// NewEndpointDataTypeBuilder() creates a EndpointDataTypeBuilder
func NewEndpointDataTypeBuilder() EndpointDataTypeBuilder {
	return &_EndpointDataTypeBuilder{_EndpointDataType: new(_EndpointDataType)}
}

type _EndpointDataTypeBuilder struct {
	*_EndpointDataType

	parentBuilder *_ExtensionObjectDefinitionBuilder

	err *utils.MultiError
}

var _ (EndpointDataTypeBuilder) = (*_EndpointDataTypeBuilder)(nil)

func (b *_EndpointDataTypeBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._EndpointDataType
}

func (b *_EndpointDataTypeBuilder) WithMandatoryFields(name PascalString, recordProperties []KeyValuePair, discoveryUrls []PascalString, networkName PascalString, port uint16) EndpointDataTypeBuilder {
	return b.WithName(name).WithRecordProperties(recordProperties...).WithDiscoveryUrls(discoveryUrls...).WithNetworkName(networkName).WithPort(port)
}

func (b *_EndpointDataTypeBuilder) WithName(name PascalString) EndpointDataTypeBuilder {
	b.Name = name
	return b
}

func (b *_EndpointDataTypeBuilder) WithNameBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) EndpointDataTypeBuilder {
	builder := builderSupplier(b.Name.CreatePascalStringBuilder())
	var err error
	b.Name, 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 *_EndpointDataTypeBuilder) WithRecordProperties(recordProperties ...KeyValuePair) EndpointDataTypeBuilder {
	b.RecordProperties = recordProperties
	return b
}

func (b *_EndpointDataTypeBuilder) WithDiscoveryUrls(discoveryUrls ...PascalString) EndpointDataTypeBuilder {
	b.DiscoveryUrls = discoveryUrls
	return b
}

func (b *_EndpointDataTypeBuilder) WithNetworkName(networkName PascalString) EndpointDataTypeBuilder {
	b.NetworkName = networkName
	return b
}

func (b *_EndpointDataTypeBuilder) WithNetworkNameBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) EndpointDataTypeBuilder {
	builder := builderSupplier(b.NetworkName.CreatePascalStringBuilder())
	var err error
	b.NetworkName, 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 *_EndpointDataTypeBuilder) WithPort(port uint16) EndpointDataTypeBuilder {
	b.Port = port
	return b
}

func (b *_EndpointDataTypeBuilder) Build() (EndpointDataType, error) {
	if b.Name == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'name' not set"))
	}
	if b.NetworkName == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'networkName' not set"))
	}
	if b.err != nil {
		return nil, errors.Wrap(b.err, "error occurred during build")
	}
	return b._EndpointDataType.deepCopy(), nil
}

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

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

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

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

// CreateEndpointDataTypeBuilder creates a EndpointDataTypeBuilder
func (b *_EndpointDataType) CreateEndpointDataTypeBuilder() EndpointDataTypeBuilder {
	if b == nil {
		return NewEndpointDataTypeBuilder()
	}
	return &_EndpointDataTypeBuilder{_EndpointDataType: b.deepCopy()}
}

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

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

func (m *_EndpointDataType) GetExtensionId() int32 {
	return int32(15559)
}

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

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

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

func (m *_EndpointDataType) GetName() PascalString {
	return m.Name
}

func (m *_EndpointDataType) GetRecordProperties() []KeyValuePair {
	return m.RecordProperties
}

func (m *_EndpointDataType) GetDiscoveryUrls() []PascalString {
	return m.DiscoveryUrls
}

func (m *_EndpointDataType) GetNetworkName() PascalString {
	return m.NetworkName
}

func (m *_EndpointDataType) GetPort() uint16 {
	return m.Port
}

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

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

func (m *_EndpointDataType) GetTypeName() string {
	return "EndpointDataType"
}

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

	// Simple field (name)
	lengthInBits += m.Name.GetLengthInBits(ctx)

	// Implicit Field (noOfRecordProperties)
	lengthInBits += 32

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

	// Implicit Field (noOfDiscoveryUrls)
	lengthInBits += 32

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

	// Simple field (networkName)
	lengthInBits += m.NetworkName.GetLengthInBits(ctx)

	// Simple field (port)
	lengthInBits += 16

	return lengthInBits
}

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

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

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

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

	recordProperties, err := ReadCountArrayField[KeyValuePair](ctx, "recordProperties", ReadComplex[KeyValuePair](ExtensionObjectDefinitionParseWithBufferProducer[KeyValuePair]((int32)(int32(14535))), readBuffer), uint64(noOfRecordProperties))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'recordProperties' field"))
	}
	m.RecordProperties = recordProperties

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

	discoveryUrls, err := ReadCountArrayField[PascalString](ctx, "discoveryUrls", ReadComplex[PascalString](PascalStringParseWithBuffer, readBuffer), uint64(noOfDiscoveryUrls))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'discoveryUrls' field"))
	}
	m.DiscoveryUrls = discoveryUrls

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

	port, err := ReadSimpleField(ctx, "port", ReadUnsignedShort(readBuffer, uint8(16)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'port' field"))
	}
	m.Port = port

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

	return m, nil
}

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

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

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

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

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

		if err := WriteSimpleField[uint16](ctx, "port", m.GetPort(), WriteUnsignedShort(writeBuffer, 16)); err != nil {
			return errors.Wrap(err, "Error serializing 'port' field")
		}

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

func (m *_EndpointDataType) IsEndpointDataType() {}

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

func (m *_EndpointDataType) deepCopy() *_EndpointDataType {
	if m == nil {
		return nil
	}
	_EndpointDataTypeCopy := &_EndpointDataType{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[PascalString](m.Name),
		utils.DeepCopySlice[KeyValuePair, KeyValuePair](m.RecordProperties),
		utils.DeepCopySlice[PascalString, PascalString](m.DiscoveryUrls),
		utils.DeepCopy[PascalString](m.NetworkName),
		m.Port,
	}
	_EndpointDataTypeCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _EndpointDataTypeCopy
}

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