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

// PublishedDataSetDataType is the corresponding interface of PublishedDataSetDataType
type PublishedDataSetDataType interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetName returns Name (property field)
	GetName() PascalString
	// GetDataSetFolder returns DataSetFolder (property field)
	GetDataSetFolder() []PascalString
	// GetDataSetMetaData returns DataSetMetaData (property field)
	GetDataSetMetaData() DataSetMetaDataType
	// GetExtensionFields returns ExtensionFields (property field)
	GetExtensionFields() []KeyValuePair
	// GetDataSetSource returns DataSetSource (property field)
	GetDataSetSource() ExtensionObject
	// IsPublishedDataSetDataType is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsPublishedDataSetDataType()
	// CreateBuilder creates a PublishedDataSetDataTypeBuilder
	CreatePublishedDataSetDataTypeBuilder() PublishedDataSetDataTypeBuilder
}

// _PublishedDataSetDataType is the data-structure of this message
type _PublishedDataSetDataType struct {
	ExtensionObjectDefinitionContract
	Name            PascalString
	DataSetFolder   []PascalString
	DataSetMetaData DataSetMetaDataType
	ExtensionFields []KeyValuePair
	DataSetSource   ExtensionObject
}

var _ PublishedDataSetDataType = (*_PublishedDataSetDataType)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_PublishedDataSetDataType)(nil)

// NewPublishedDataSetDataType factory function for _PublishedDataSetDataType
func NewPublishedDataSetDataType(name PascalString, dataSetFolder []PascalString, dataSetMetaData DataSetMetaDataType, extensionFields []KeyValuePair, dataSetSource ExtensionObject) *_PublishedDataSetDataType {
	if name == nil {
		panic("name of type PascalString for PublishedDataSetDataType must not be nil")
	}
	if dataSetMetaData == nil {
		panic("dataSetMetaData of type DataSetMetaDataType for PublishedDataSetDataType must not be nil")
	}
	if dataSetSource == nil {
		panic("dataSetSource of type ExtensionObject for PublishedDataSetDataType must not be nil")
	}
	_result := &_PublishedDataSetDataType{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		Name:                              name,
		DataSetFolder:                     dataSetFolder,
		DataSetMetaData:                   dataSetMetaData,
		ExtensionFields:                   extensionFields,
		DataSetSource:                     dataSetSource,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// PublishedDataSetDataTypeBuilder is a builder for PublishedDataSetDataType
type PublishedDataSetDataTypeBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(name PascalString, dataSetFolder []PascalString, dataSetMetaData DataSetMetaDataType, extensionFields []KeyValuePair, dataSetSource ExtensionObject) PublishedDataSetDataTypeBuilder
	// WithName adds Name (property field)
	WithName(PascalString) PublishedDataSetDataTypeBuilder
	// WithNameBuilder adds Name (property field) which is build by the builder
	WithNameBuilder(func(PascalStringBuilder) PascalStringBuilder) PublishedDataSetDataTypeBuilder
	// WithDataSetFolder adds DataSetFolder (property field)
	WithDataSetFolder(...PascalString) PublishedDataSetDataTypeBuilder
	// WithDataSetMetaData adds DataSetMetaData (property field)
	WithDataSetMetaData(DataSetMetaDataType) PublishedDataSetDataTypeBuilder
	// WithDataSetMetaDataBuilder adds DataSetMetaData (property field) which is build by the builder
	WithDataSetMetaDataBuilder(func(DataSetMetaDataTypeBuilder) DataSetMetaDataTypeBuilder) PublishedDataSetDataTypeBuilder
	// WithExtensionFields adds ExtensionFields (property field)
	WithExtensionFields(...KeyValuePair) PublishedDataSetDataTypeBuilder
	// WithDataSetSource adds DataSetSource (property field)
	WithDataSetSource(ExtensionObject) PublishedDataSetDataTypeBuilder
	// WithDataSetSourceBuilder adds DataSetSource (property field) which is build by the builder
	WithDataSetSourceBuilder(func(ExtensionObjectBuilder) ExtensionObjectBuilder) PublishedDataSetDataTypeBuilder
	// 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 PublishedDataSetDataType or returns an error if something is wrong
	Build() (PublishedDataSetDataType, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() PublishedDataSetDataType
}

// NewPublishedDataSetDataTypeBuilder() creates a PublishedDataSetDataTypeBuilder
func NewPublishedDataSetDataTypeBuilder() PublishedDataSetDataTypeBuilder {
	return &_PublishedDataSetDataTypeBuilder{_PublishedDataSetDataType: new(_PublishedDataSetDataType)}
}

type _PublishedDataSetDataTypeBuilder struct {
	*_PublishedDataSetDataType

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (PublishedDataSetDataTypeBuilder) = (*_PublishedDataSetDataTypeBuilder)(nil)

func (b *_PublishedDataSetDataTypeBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._PublishedDataSetDataType
}

func (b *_PublishedDataSetDataTypeBuilder) WithMandatoryFields(name PascalString, dataSetFolder []PascalString, dataSetMetaData DataSetMetaDataType, extensionFields []KeyValuePair, dataSetSource ExtensionObject) PublishedDataSetDataTypeBuilder {
	return b.WithName(name).WithDataSetFolder(dataSetFolder...).WithDataSetMetaData(dataSetMetaData).WithExtensionFields(extensionFields...).WithDataSetSource(dataSetSource)
}

func (b *_PublishedDataSetDataTypeBuilder) WithName(name PascalString) PublishedDataSetDataTypeBuilder {
	b.Name = name
	return b
}

func (b *_PublishedDataSetDataTypeBuilder) WithNameBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) PublishedDataSetDataTypeBuilder {
	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 *_PublishedDataSetDataTypeBuilder) WithDataSetFolder(dataSetFolder ...PascalString) PublishedDataSetDataTypeBuilder {
	b.DataSetFolder = dataSetFolder
	return b
}

func (b *_PublishedDataSetDataTypeBuilder) WithDataSetMetaData(dataSetMetaData DataSetMetaDataType) PublishedDataSetDataTypeBuilder {
	b.DataSetMetaData = dataSetMetaData
	return b
}

func (b *_PublishedDataSetDataTypeBuilder) WithDataSetMetaDataBuilder(builderSupplier func(DataSetMetaDataTypeBuilder) DataSetMetaDataTypeBuilder) PublishedDataSetDataTypeBuilder {
	builder := builderSupplier(b.DataSetMetaData.CreateDataSetMetaDataTypeBuilder())
	var err error
	b.DataSetMetaData, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "DataSetMetaDataTypeBuilder failed"))
	}
	return b
}

func (b *_PublishedDataSetDataTypeBuilder) WithExtensionFields(extensionFields ...KeyValuePair) PublishedDataSetDataTypeBuilder {
	b.ExtensionFields = extensionFields
	return b
}

func (b *_PublishedDataSetDataTypeBuilder) WithDataSetSource(dataSetSource ExtensionObject) PublishedDataSetDataTypeBuilder {
	b.DataSetSource = dataSetSource
	return b
}

func (b *_PublishedDataSetDataTypeBuilder) WithDataSetSourceBuilder(builderSupplier func(ExtensionObjectBuilder) ExtensionObjectBuilder) PublishedDataSetDataTypeBuilder {
	builder := builderSupplier(b.DataSetSource.CreateExtensionObjectBuilder())
	var err error
	b.DataSetSource, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "ExtensionObjectBuilder failed"))
	}
	return b
}

func (b *_PublishedDataSetDataTypeBuilder) Build() (PublishedDataSetDataType, error) {
	if b.Name == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'name' not set"))
	}
	if b.DataSetMetaData == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'dataSetMetaData' not set"))
	}
	if b.DataSetSource == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'dataSetSource' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._PublishedDataSetDataType.deepCopy(), nil
}

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

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

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

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

// CreatePublishedDataSetDataTypeBuilder creates a PublishedDataSetDataTypeBuilder
func (b *_PublishedDataSetDataType) CreatePublishedDataSetDataTypeBuilder() PublishedDataSetDataTypeBuilder {
	if b == nil {
		return NewPublishedDataSetDataTypeBuilder()
	}
	return &_PublishedDataSetDataTypeBuilder{_PublishedDataSetDataType: b.deepCopy()}
}

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

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

func (m *_PublishedDataSetDataType) GetExtensionId() int32 {
	return int32(15580)
}

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

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

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

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

func (m *_PublishedDataSetDataType) GetDataSetFolder() []PascalString {
	return m.DataSetFolder
}

func (m *_PublishedDataSetDataType) GetDataSetMetaData() DataSetMetaDataType {
	return m.DataSetMetaData
}

func (m *_PublishedDataSetDataType) GetExtensionFields() []KeyValuePair {
	return m.ExtensionFields
}

func (m *_PublishedDataSetDataType) GetDataSetSource() ExtensionObject {
	return m.DataSetSource
}

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

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

func (m *_PublishedDataSetDataType) GetTypeName() string {
	return "PublishedDataSetDataType"
}

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

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

	// Implicit Field (noOfDataSetFolder)
	lengthInBits += 32

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

	// Simple field (dataSetMetaData)
	lengthInBits += m.DataSetMetaData.GetLengthInBits(ctx)

	// Implicit Field (noOfExtensionFields)
	lengthInBits += 32

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

	// Simple field (dataSetSource)
	lengthInBits += m.DataSetSource.GetLengthInBits(ctx)

	return lengthInBits
}

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

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

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

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

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

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

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

	dataSetSource, err := ReadSimpleField[ExtensionObject](ctx, "dataSetSource", ReadComplex[ExtensionObject](ExtensionObjectParseWithBufferProducer[ExtensionObject]((bool)(bool(true))), readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'dataSetSource' field"))
	}
	m.DataSetSource = dataSetSource

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

	return m, nil
}

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

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

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

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

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

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

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

func (m *_PublishedDataSetDataType) IsPublishedDataSetDataType() {}

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

func (m *_PublishedDataSetDataType) deepCopy() *_PublishedDataSetDataType {
	if m == nil {
		return nil
	}
	_PublishedDataSetDataTypeCopy := &_PublishedDataSetDataType{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[PascalString](m.Name),
		utils.DeepCopySlice[PascalString, PascalString](m.DataSetFolder),
		utils.DeepCopy[DataSetMetaDataType](m.DataSetMetaData),
		utils.DeepCopySlice[KeyValuePair, KeyValuePair](m.ExtensionFields),
		utils.DeepCopy[ExtensionObject](m.DataSetSource),
	}
	_PublishedDataSetDataTypeCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _PublishedDataSetDataTypeCopy
}

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