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

// DataTypeSchemaHeader is the corresponding interface of DataTypeSchemaHeader
type DataTypeSchemaHeader interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetNamespaces returns Namespaces (property field)
	GetNamespaces() []PascalString
	// GetStructureDataTypes returns StructureDataTypes (property field)
	GetStructureDataTypes() []StructureDescription
	// GetEnumDataTypes returns EnumDataTypes (property field)
	GetEnumDataTypes() []EnumDescription
	// GetSimpleDataTypes returns SimpleDataTypes (property field)
	GetSimpleDataTypes() []SimpleTypeDescription
	// IsDataTypeSchemaHeader is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsDataTypeSchemaHeader()
	// CreateBuilder creates a DataTypeSchemaHeaderBuilder
	CreateDataTypeSchemaHeaderBuilder() DataTypeSchemaHeaderBuilder
}

// _DataTypeSchemaHeader is the data-structure of this message
type _DataTypeSchemaHeader struct {
	ExtensionObjectDefinitionContract
	Namespaces         []PascalString
	StructureDataTypes []StructureDescription
	EnumDataTypes      []EnumDescription
	SimpleDataTypes    []SimpleTypeDescription
}

var _ DataTypeSchemaHeader = (*_DataTypeSchemaHeader)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_DataTypeSchemaHeader)(nil)

// NewDataTypeSchemaHeader factory function for _DataTypeSchemaHeader
func NewDataTypeSchemaHeader(namespaces []PascalString, structureDataTypes []StructureDescription, enumDataTypes []EnumDescription, simpleDataTypes []SimpleTypeDescription) *_DataTypeSchemaHeader {
	_result := &_DataTypeSchemaHeader{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		Namespaces:                        namespaces,
		StructureDataTypes:                structureDataTypes,
		EnumDataTypes:                     enumDataTypes,
		SimpleDataTypes:                   simpleDataTypes,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// DataTypeSchemaHeaderBuilder is a builder for DataTypeSchemaHeader
type DataTypeSchemaHeaderBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(namespaces []PascalString, structureDataTypes []StructureDescription, enumDataTypes []EnumDescription, simpleDataTypes []SimpleTypeDescription) DataTypeSchemaHeaderBuilder
	// WithNamespaces adds Namespaces (property field)
	WithNamespaces(...PascalString) DataTypeSchemaHeaderBuilder
	// WithStructureDataTypes adds StructureDataTypes (property field)
	WithStructureDataTypes(...StructureDescription) DataTypeSchemaHeaderBuilder
	// WithEnumDataTypes adds EnumDataTypes (property field)
	WithEnumDataTypes(...EnumDescription) DataTypeSchemaHeaderBuilder
	// WithSimpleDataTypes adds SimpleDataTypes (property field)
	WithSimpleDataTypes(...SimpleTypeDescription) DataTypeSchemaHeaderBuilder
	// 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 DataTypeSchemaHeader or returns an error if something is wrong
	Build() (DataTypeSchemaHeader, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() DataTypeSchemaHeader
}

// NewDataTypeSchemaHeaderBuilder() creates a DataTypeSchemaHeaderBuilder
func NewDataTypeSchemaHeaderBuilder() DataTypeSchemaHeaderBuilder {
	return &_DataTypeSchemaHeaderBuilder{_DataTypeSchemaHeader: new(_DataTypeSchemaHeader)}
}

type _DataTypeSchemaHeaderBuilder struct {
	*_DataTypeSchemaHeader

	parentBuilder *_ExtensionObjectDefinitionBuilder

	err *utils.MultiError
}

var _ (DataTypeSchemaHeaderBuilder) = (*_DataTypeSchemaHeaderBuilder)(nil)

func (b *_DataTypeSchemaHeaderBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._DataTypeSchemaHeader
}

func (b *_DataTypeSchemaHeaderBuilder) WithMandatoryFields(namespaces []PascalString, structureDataTypes []StructureDescription, enumDataTypes []EnumDescription, simpleDataTypes []SimpleTypeDescription) DataTypeSchemaHeaderBuilder {
	return b.WithNamespaces(namespaces...).WithStructureDataTypes(structureDataTypes...).WithEnumDataTypes(enumDataTypes...).WithSimpleDataTypes(simpleDataTypes...)
}

func (b *_DataTypeSchemaHeaderBuilder) WithNamespaces(namespaces ...PascalString) DataTypeSchemaHeaderBuilder {
	b.Namespaces = namespaces
	return b
}

func (b *_DataTypeSchemaHeaderBuilder) WithStructureDataTypes(structureDataTypes ...StructureDescription) DataTypeSchemaHeaderBuilder {
	b.StructureDataTypes = structureDataTypes
	return b
}

func (b *_DataTypeSchemaHeaderBuilder) WithEnumDataTypes(enumDataTypes ...EnumDescription) DataTypeSchemaHeaderBuilder {
	b.EnumDataTypes = enumDataTypes
	return b
}

func (b *_DataTypeSchemaHeaderBuilder) WithSimpleDataTypes(simpleDataTypes ...SimpleTypeDescription) DataTypeSchemaHeaderBuilder {
	b.SimpleDataTypes = simpleDataTypes
	return b
}

func (b *_DataTypeSchemaHeaderBuilder) Build() (DataTypeSchemaHeader, error) {
	if b.err != nil {
		return nil, errors.Wrap(b.err, "error occurred during build")
	}
	return b._DataTypeSchemaHeader.deepCopy(), nil
}

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

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

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

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

// CreateDataTypeSchemaHeaderBuilder creates a DataTypeSchemaHeaderBuilder
func (b *_DataTypeSchemaHeader) CreateDataTypeSchemaHeaderBuilder() DataTypeSchemaHeaderBuilder {
	if b == nil {
		return NewDataTypeSchemaHeaderBuilder()
	}
	return &_DataTypeSchemaHeaderBuilder{_DataTypeSchemaHeader: b.deepCopy()}
}

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

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

func (m *_DataTypeSchemaHeader) GetExtensionId() int32 {
	return int32(15536)
}

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

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

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

func (m *_DataTypeSchemaHeader) GetNamespaces() []PascalString {
	return m.Namespaces
}

func (m *_DataTypeSchemaHeader) GetStructureDataTypes() []StructureDescription {
	return m.StructureDataTypes
}

func (m *_DataTypeSchemaHeader) GetEnumDataTypes() []EnumDescription {
	return m.EnumDataTypes
}

func (m *_DataTypeSchemaHeader) GetSimpleDataTypes() []SimpleTypeDescription {
	return m.SimpleDataTypes
}

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

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

func (m *_DataTypeSchemaHeader) GetTypeName() string {
	return "DataTypeSchemaHeader"
}

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

	// Implicit Field (noOfNamespaces)
	lengthInBits += 32

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

	// Implicit Field (noOfStructureDataTypes)
	lengthInBits += 32

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

	// Implicit Field (noOfEnumDataTypes)
	lengthInBits += 32

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

	// Implicit Field (noOfSimpleDataTypes)
	lengthInBits += 32

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

	return lengthInBits
}

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

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

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

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

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

	structureDataTypes, err := ReadCountArrayField[StructureDescription](ctx, "structureDataTypes", ReadComplex[StructureDescription](ExtensionObjectDefinitionParseWithBufferProducer[StructureDescription]((int32)(int32(15489))), readBuffer), uint64(noOfStructureDataTypes))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'structureDataTypes' field"))
	}
	m.StructureDataTypes = structureDataTypes

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

	enumDataTypes, err := ReadCountArrayField[EnumDescription](ctx, "enumDataTypes", ReadComplex[EnumDescription](ExtensionObjectDefinitionParseWithBufferProducer[EnumDescription]((int32)(int32(15490))), readBuffer), uint64(noOfEnumDataTypes))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'enumDataTypes' field"))
	}
	m.EnumDataTypes = enumDataTypes

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

	simpleDataTypes, err := ReadCountArrayField[SimpleTypeDescription](ctx, "simpleDataTypes", ReadComplex[SimpleTypeDescription](ExtensionObjectDefinitionParseWithBufferProducer[SimpleTypeDescription]((int32)(int32(15007))), readBuffer), uint64(noOfSimpleDataTypes))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'simpleDataTypes' field"))
	}
	m.SimpleDataTypes = simpleDataTypes

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

	return m, nil
}

func (m *_DataTypeSchemaHeader) 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 *_DataTypeSchemaHeader) SerializeWithWriteBuffer(ctx context.Context, writeBuffer utils.WriteBuffer) error {
	positionAware := writeBuffer
	_ = positionAware
	log := zerolog.Ctx(ctx)
	_ = log
	ser := func() error {
		if pushErr := writeBuffer.PushContext("DataTypeSchemaHeader"); pushErr != nil {
			return errors.Wrap(pushErr, "Error pushing for DataTypeSchemaHeader")
		}
		noOfNamespaces := int32(utils.InlineIf(bool((m.GetNamespaces()) == (nil)), func() any { return int32(-(int32(1))) }, func() any { return int32(int32(len(m.GetNamespaces()))) }).(int32))
		if err := WriteImplicitField(ctx, "noOfNamespaces", noOfNamespaces, WriteSignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'noOfNamespaces' field")
		}

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

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

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

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

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

func (m *_DataTypeSchemaHeader) IsDataTypeSchemaHeader() {}

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

func (m *_DataTypeSchemaHeader) deepCopy() *_DataTypeSchemaHeader {
	if m == nil {
		return nil
	}
	_DataTypeSchemaHeaderCopy := &_DataTypeSchemaHeader{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopySlice[PascalString, PascalString](m.Namespaces),
		utils.DeepCopySlice[StructureDescription, StructureDescription](m.StructureDataTypes),
		utils.DeepCopySlice[EnumDescription, EnumDescription](m.EnumDataTypes),
		utils.DeepCopySlice[SimpleTypeDescription, SimpleTypeDescription](m.SimpleDataTypes),
	}
	_DataTypeSchemaHeaderCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _DataTypeSchemaHeaderCopy
}

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