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

// QualifiedName is the corresponding interface of QualifiedName
type QualifiedName interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	// GetNamespaceIndex returns NamespaceIndex (property field)
	// A string qualified with a namespace index.
	GetNamespaceIndex() uint16
	// GetName returns Name (property field)
	GetName() PascalString
	// IsQualifiedName is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsQualifiedName()
	// CreateBuilder creates a QualifiedNameBuilder
	CreateQualifiedNameBuilder() QualifiedNameBuilder
}

// _QualifiedName is the data-structure of this message
type _QualifiedName struct {
	NamespaceIndex uint16
	Name           PascalString
}

var _ QualifiedName = (*_QualifiedName)(nil)

// NewQualifiedName factory function for _QualifiedName
func NewQualifiedName(namespaceIndex uint16, name PascalString) *_QualifiedName {
	if name == nil {
		panic("name of type PascalString for QualifiedName must not be nil")
	}
	return &_QualifiedName{NamespaceIndex: namespaceIndex, Name: name}
}

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

// QualifiedNameBuilder is a builder for QualifiedName
type QualifiedNameBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(namespaceIndex uint16, name PascalString) QualifiedNameBuilder
	// WithNamespaceIndex adds NamespaceIndex (property field)
	WithNamespaceIndex(uint16) QualifiedNameBuilder
	// WithName adds Name (property field)
	WithName(PascalString) QualifiedNameBuilder
	// WithNameBuilder adds Name (property field) which is build by the builder
	WithNameBuilder(func(PascalStringBuilder) PascalStringBuilder) QualifiedNameBuilder
	// Build builds the QualifiedName or returns an error if something is wrong
	Build() (QualifiedName, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() QualifiedName
}

// NewQualifiedNameBuilder() creates a QualifiedNameBuilder
func NewQualifiedNameBuilder() QualifiedNameBuilder {
	return &_QualifiedNameBuilder{_QualifiedName: new(_QualifiedName)}
}

type _QualifiedNameBuilder struct {
	*_QualifiedName

	collectedErr []error
}

var _ (QualifiedNameBuilder) = (*_QualifiedNameBuilder)(nil)

func (b *_QualifiedNameBuilder) WithMandatoryFields(namespaceIndex uint16, name PascalString) QualifiedNameBuilder {
	return b.WithNamespaceIndex(namespaceIndex).WithName(name)
}

func (b *_QualifiedNameBuilder) WithNamespaceIndex(namespaceIndex uint16) QualifiedNameBuilder {
	b.NamespaceIndex = namespaceIndex
	return b
}

func (b *_QualifiedNameBuilder) WithName(name PascalString) QualifiedNameBuilder {
	b.Name = name
	return b
}

func (b *_QualifiedNameBuilder) WithNameBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) QualifiedNameBuilder {
	builder := builderSupplier(b.Name.CreatePascalStringBuilder())
	var err error
	b.Name, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "PascalStringBuilder failed"))
	}
	return b
}

func (b *_QualifiedNameBuilder) Build() (QualifiedName, error) {
	if b.Name == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'name' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._QualifiedName.deepCopy(), nil
}

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

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

// CreateQualifiedNameBuilder creates a QualifiedNameBuilder
func (b *_QualifiedName) CreateQualifiedNameBuilder() QualifiedNameBuilder {
	if b == nil {
		return NewQualifiedNameBuilder()
	}
	return &_QualifiedNameBuilder{_QualifiedName: b.deepCopy()}
}

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

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

func (m *_QualifiedName) GetNamespaceIndex() uint16 {
	return m.NamespaceIndex
}

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

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

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

func (m *_QualifiedName) GetTypeName() string {
	return "QualifiedName"
}

func (m *_QualifiedName) GetLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(0)

	// Simple field (namespaceIndex)
	lengthInBits += 16

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

	return lengthInBits
}

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

func QualifiedNameParse(ctx context.Context, theBytes []byte) (QualifiedName, error) {
	return QualifiedNameParseWithBuffer(ctx, utils.NewReadBufferByteBased(theBytes))
}

func QualifiedNameParseWithBufferProducer() func(ctx context.Context, readBuffer utils.ReadBuffer) (QualifiedName, error) {
	return func(ctx context.Context, readBuffer utils.ReadBuffer) (QualifiedName, error) {
		return QualifiedNameParseWithBuffer(ctx, readBuffer)
	}
}

func QualifiedNameParseWithBuffer(ctx context.Context, readBuffer utils.ReadBuffer) (QualifiedName, error) {
	v, err := (new(_QualifiedName)).parse(ctx, readBuffer)
	if err != nil {
		return nil, err
	}
	return v, nil
}

func (m *_QualifiedName) parse(ctx context.Context, readBuffer utils.ReadBuffer) (__qualifiedName QualifiedName, err error) {
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("QualifiedName"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for QualifiedName")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

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

	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

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

	return m, nil
}

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

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

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

	if popErr := writeBuffer.PopContext("QualifiedName"); popErr != nil {
		return errors.Wrap(popErr, "Error popping for QualifiedName")
	}
	return nil
}

func (m *_QualifiedName) IsQualifiedName() {}

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

func (m *_QualifiedName) deepCopy() *_QualifiedName {
	if m == nil {
		return nil
	}
	_QualifiedNameCopy := &_QualifiedName{
		m.NamespaceIndex,
		utils.DeepCopy[PascalString](m.Name),
	}
	return _QualifiedNameCopy
}

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