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

// StructureDescription is the corresponding interface of StructureDescription
type StructureDescription interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetDataTypeId returns DataTypeId (property field)
	GetDataTypeId() NodeId
	// GetName returns Name (property field)
	GetName() QualifiedName
	// GetStructureDefinition returns StructureDefinition (property field)
	GetStructureDefinition() StructureDefinition
	// IsStructureDescription is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsStructureDescription()
	// CreateBuilder creates a StructureDescriptionBuilder
	CreateStructureDescriptionBuilder() StructureDescriptionBuilder
}

// _StructureDescription is the data-structure of this message
type _StructureDescription struct {
	ExtensionObjectDefinitionContract
	DataTypeId          NodeId
	Name                QualifiedName
	StructureDefinition StructureDefinition
}

var _ StructureDescription = (*_StructureDescription)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_StructureDescription)(nil)

// NewStructureDescription factory function for _StructureDescription
func NewStructureDescription(dataTypeId NodeId, name QualifiedName, structureDefinition StructureDefinition) *_StructureDescription {
	if dataTypeId == nil {
		panic("dataTypeId of type NodeId for StructureDescription must not be nil")
	}
	if name == nil {
		panic("name of type QualifiedName for StructureDescription must not be nil")
	}
	if structureDefinition == nil {
		panic("structureDefinition of type StructureDefinition for StructureDescription must not be nil")
	}
	_result := &_StructureDescription{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		DataTypeId:                        dataTypeId,
		Name:                              name,
		StructureDefinition:               structureDefinition,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// StructureDescriptionBuilder is a builder for StructureDescription
type StructureDescriptionBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(dataTypeId NodeId, name QualifiedName, structureDefinition StructureDefinition) StructureDescriptionBuilder
	// WithDataTypeId adds DataTypeId (property field)
	WithDataTypeId(NodeId) StructureDescriptionBuilder
	// WithDataTypeIdBuilder adds DataTypeId (property field) which is build by the builder
	WithDataTypeIdBuilder(func(NodeIdBuilder) NodeIdBuilder) StructureDescriptionBuilder
	// WithName adds Name (property field)
	WithName(QualifiedName) StructureDescriptionBuilder
	// WithNameBuilder adds Name (property field) which is build by the builder
	WithNameBuilder(func(QualifiedNameBuilder) QualifiedNameBuilder) StructureDescriptionBuilder
	// WithStructureDefinition adds StructureDefinition (property field)
	WithStructureDefinition(StructureDefinition) StructureDescriptionBuilder
	// WithStructureDefinitionBuilder adds StructureDefinition (property field) which is build by the builder
	WithStructureDefinitionBuilder(func(StructureDefinitionBuilder) StructureDefinitionBuilder) StructureDescriptionBuilder
	// 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 StructureDescription or returns an error if something is wrong
	Build() (StructureDescription, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() StructureDescription
}

// NewStructureDescriptionBuilder() creates a StructureDescriptionBuilder
func NewStructureDescriptionBuilder() StructureDescriptionBuilder {
	return &_StructureDescriptionBuilder{_StructureDescription: new(_StructureDescription)}
}

type _StructureDescriptionBuilder struct {
	*_StructureDescription

	parentBuilder *_ExtensionObjectDefinitionBuilder

	err *utils.MultiError
}

var _ (StructureDescriptionBuilder) = (*_StructureDescriptionBuilder)(nil)

func (b *_StructureDescriptionBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._StructureDescription
}

func (b *_StructureDescriptionBuilder) WithMandatoryFields(dataTypeId NodeId, name QualifiedName, structureDefinition StructureDefinition) StructureDescriptionBuilder {
	return b.WithDataTypeId(dataTypeId).WithName(name).WithStructureDefinition(structureDefinition)
}

func (b *_StructureDescriptionBuilder) WithDataTypeId(dataTypeId NodeId) StructureDescriptionBuilder {
	b.DataTypeId = dataTypeId
	return b
}

func (b *_StructureDescriptionBuilder) WithDataTypeIdBuilder(builderSupplier func(NodeIdBuilder) NodeIdBuilder) StructureDescriptionBuilder {
	builder := builderSupplier(b.DataTypeId.CreateNodeIdBuilder())
	var err error
	b.DataTypeId, 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, "NodeIdBuilder failed"))
	}
	return b
}

func (b *_StructureDescriptionBuilder) WithName(name QualifiedName) StructureDescriptionBuilder {
	b.Name = name
	return b
}

func (b *_StructureDescriptionBuilder) WithNameBuilder(builderSupplier func(QualifiedNameBuilder) QualifiedNameBuilder) StructureDescriptionBuilder {
	builder := builderSupplier(b.Name.CreateQualifiedNameBuilder())
	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, "QualifiedNameBuilder failed"))
	}
	return b
}

func (b *_StructureDescriptionBuilder) WithStructureDefinition(structureDefinition StructureDefinition) StructureDescriptionBuilder {
	b.StructureDefinition = structureDefinition
	return b
}

func (b *_StructureDescriptionBuilder) WithStructureDefinitionBuilder(builderSupplier func(StructureDefinitionBuilder) StructureDefinitionBuilder) StructureDescriptionBuilder {
	builder := builderSupplier(b.StructureDefinition.CreateStructureDefinitionBuilder())
	var err error
	b.StructureDefinition, 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, "StructureDefinitionBuilder failed"))
	}
	return b
}

func (b *_StructureDescriptionBuilder) Build() (StructureDescription, error) {
	if b.DataTypeId == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'dataTypeId' not set"))
	}
	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.StructureDefinition == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'structureDefinition' not set"))
	}
	if b.err != nil {
		return nil, errors.Wrap(b.err, "error occurred during build")
	}
	return b._StructureDescription.deepCopy(), nil
}

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

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

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

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

// CreateStructureDescriptionBuilder creates a StructureDescriptionBuilder
func (b *_StructureDescription) CreateStructureDescriptionBuilder() StructureDescriptionBuilder {
	if b == nil {
		return NewStructureDescriptionBuilder()
	}
	return &_StructureDescriptionBuilder{_StructureDescription: b.deepCopy()}
}

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

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

func (m *_StructureDescription) GetExtensionId() int32 {
	return int32(15489)
}

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

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

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

func (m *_StructureDescription) GetDataTypeId() NodeId {
	return m.DataTypeId
}

func (m *_StructureDescription) GetName() QualifiedName {
	return m.Name
}

func (m *_StructureDescription) GetStructureDefinition() StructureDefinition {
	return m.StructureDefinition
}

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

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

func (m *_StructureDescription) GetTypeName() string {
	return "StructureDescription"
}

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

	// Simple field (dataTypeId)
	lengthInBits += m.DataTypeId.GetLengthInBits(ctx)

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

	// Simple field (structureDefinition)
	lengthInBits += m.StructureDefinition.GetLengthInBits(ctx)

	return lengthInBits
}

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

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

	dataTypeId, err := ReadSimpleField[NodeId](ctx, "dataTypeId", ReadComplex[NodeId](NodeIdParseWithBuffer, readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'dataTypeId' field"))
	}
	m.DataTypeId = dataTypeId

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

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

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

	return m, nil
}

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

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

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

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

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

func (m *_StructureDescription) IsStructureDescription() {}

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

func (m *_StructureDescription) deepCopy() *_StructureDescription {
	if m == nil {
		return nil
	}
	_StructureDescriptionCopy := &_StructureDescription{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[NodeId](m.DataTypeId),
		utils.DeepCopy[QualifiedName](m.Name),
		utils.DeepCopy[StructureDefinition](m.StructureDefinition),
	}
	_StructureDescriptionCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _StructureDescriptionCopy
}

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