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

// MdnsDiscoveryConfiguration is the corresponding interface of MdnsDiscoveryConfiguration
type MdnsDiscoveryConfiguration interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetMdnsServerName returns MdnsServerName (property field)
	GetMdnsServerName() PascalString
	// GetServerCapabilities returns ServerCapabilities (property field)
	GetServerCapabilities() []PascalString
	// IsMdnsDiscoveryConfiguration is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsMdnsDiscoveryConfiguration()
	// CreateBuilder creates a MdnsDiscoveryConfigurationBuilder
	CreateMdnsDiscoveryConfigurationBuilder() MdnsDiscoveryConfigurationBuilder
}

// _MdnsDiscoveryConfiguration is the data-structure of this message
type _MdnsDiscoveryConfiguration struct {
	ExtensionObjectDefinitionContract
	MdnsServerName     PascalString
	ServerCapabilities []PascalString
}

var _ MdnsDiscoveryConfiguration = (*_MdnsDiscoveryConfiguration)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_MdnsDiscoveryConfiguration)(nil)

// NewMdnsDiscoveryConfiguration factory function for _MdnsDiscoveryConfiguration
func NewMdnsDiscoveryConfiguration(mdnsServerName PascalString, serverCapabilities []PascalString) *_MdnsDiscoveryConfiguration {
	if mdnsServerName == nil {
		panic("mdnsServerName of type PascalString for MdnsDiscoveryConfiguration must not be nil")
	}
	_result := &_MdnsDiscoveryConfiguration{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		MdnsServerName:                    mdnsServerName,
		ServerCapabilities:                serverCapabilities,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// MdnsDiscoveryConfigurationBuilder is a builder for MdnsDiscoveryConfiguration
type MdnsDiscoveryConfigurationBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(mdnsServerName PascalString, serverCapabilities []PascalString) MdnsDiscoveryConfigurationBuilder
	// WithMdnsServerName adds MdnsServerName (property field)
	WithMdnsServerName(PascalString) MdnsDiscoveryConfigurationBuilder
	// WithMdnsServerNameBuilder adds MdnsServerName (property field) which is build by the builder
	WithMdnsServerNameBuilder(func(PascalStringBuilder) PascalStringBuilder) MdnsDiscoveryConfigurationBuilder
	// WithServerCapabilities adds ServerCapabilities (property field)
	WithServerCapabilities(...PascalString) MdnsDiscoveryConfigurationBuilder
	// 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 MdnsDiscoveryConfiguration or returns an error if something is wrong
	Build() (MdnsDiscoveryConfiguration, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() MdnsDiscoveryConfiguration
}

// NewMdnsDiscoveryConfigurationBuilder() creates a MdnsDiscoveryConfigurationBuilder
func NewMdnsDiscoveryConfigurationBuilder() MdnsDiscoveryConfigurationBuilder {
	return &_MdnsDiscoveryConfigurationBuilder{_MdnsDiscoveryConfiguration: new(_MdnsDiscoveryConfiguration)}
}

type _MdnsDiscoveryConfigurationBuilder struct {
	*_MdnsDiscoveryConfiguration

	parentBuilder *_ExtensionObjectDefinitionBuilder

	err *utils.MultiError
}

var _ (MdnsDiscoveryConfigurationBuilder) = (*_MdnsDiscoveryConfigurationBuilder)(nil)

func (b *_MdnsDiscoveryConfigurationBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._MdnsDiscoveryConfiguration
}

func (b *_MdnsDiscoveryConfigurationBuilder) WithMandatoryFields(mdnsServerName PascalString, serverCapabilities []PascalString) MdnsDiscoveryConfigurationBuilder {
	return b.WithMdnsServerName(mdnsServerName).WithServerCapabilities(serverCapabilities...)
}

func (b *_MdnsDiscoveryConfigurationBuilder) WithMdnsServerName(mdnsServerName PascalString) MdnsDiscoveryConfigurationBuilder {
	b.MdnsServerName = mdnsServerName
	return b
}

func (b *_MdnsDiscoveryConfigurationBuilder) WithMdnsServerNameBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) MdnsDiscoveryConfigurationBuilder {
	builder := builderSupplier(b.MdnsServerName.CreatePascalStringBuilder())
	var err error
	b.MdnsServerName, 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 *_MdnsDiscoveryConfigurationBuilder) WithServerCapabilities(serverCapabilities ...PascalString) MdnsDiscoveryConfigurationBuilder {
	b.ServerCapabilities = serverCapabilities
	return b
}

func (b *_MdnsDiscoveryConfigurationBuilder) Build() (MdnsDiscoveryConfiguration, error) {
	if b.MdnsServerName == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'mdnsServerName' not set"))
	}
	if b.err != nil {
		return nil, errors.Wrap(b.err, "error occurred during build")
	}
	return b._MdnsDiscoveryConfiguration.deepCopy(), nil
}

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

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

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

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

// CreateMdnsDiscoveryConfigurationBuilder creates a MdnsDiscoveryConfigurationBuilder
func (b *_MdnsDiscoveryConfiguration) CreateMdnsDiscoveryConfigurationBuilder() MdnsDiscoveryConfigurationBuilder {
	if b == nil {
		return NewMdnsDiscoveryConfigurationBuilder()
	}
	return &_MdnsDiscoveryConfigurationBuilder{_MdnsDiscoveryConfiguration: b.deepCopy()}
}

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

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

func (m *_MdnsDiscoveryConfiguration) GetExtensionId() int32 {
	return int32(12893)
}

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

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

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

func (m *_MdnsDiscoveryConfiguration) GetMdnsServerName() PascalString {
	return m.MdnsServerName
}

func (m *_MdnsDiscoveryConfiguration) GetServerCapabilities() []PascalString {
	return m.ServerCapabilities
}

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

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

func (m *_MdnsDiscoveryConfiguration) GetTypeName() string {
	return "MdnsDiscoveryConfiguration"
}

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

	// Simple field (mdnsServerName)
	lengthInBits += m.MdnsServerName.GetLengthInBits(ctx)

	// Implicit Field (noOfServerCapabilities)
	lengthInBits += 32

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

	return lengthInBits
}

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

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

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

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

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

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

	return m, nil
}

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

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

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

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

func (m *_MdnsDiscoveryConfiguration) IsMdnsDiscoveryConfiguration() {}

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

func (m *_MdnsDiscoveryConfiguration) deepCopy() *_MdnsDiscoveryConfiguration {
	if m == nil {
		return nil
	}
	_MdnsDiscoveryConfigurationCopy := &_MdnsDiscoveryConfiguration{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[PascalString](m.MdnsServerName),
		utils.DeepCopySlice[PascalString, PascalString](m.ServerCapabilities),
	}
	_MdnsDiscoveryConfigurationCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _MdnsDiscoveryConfigurationCopy
}

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