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

// EnumDefinition is the corresponding interface of EnumDefinition
type EnumDefinition interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetFields returns Fields (property field)
	GetFields() []EnumField
	// IsEnumDefinition is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsEnumDefinition()
	// CreateBuilder creates a EnumDefinitionBuilder
	CreateEnumDefinitionBuilder() EnumDefinitionBuilder
}

// _EnumDefinition is the data-structure of this message
type _EnumDefinition struct {
	ExtensionObjectDefinitionContract
	Fields []EnumField
}

var _ EnumDefinition = (*_EnumDefinition)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_EnumDefinition)(nil)

// NewEnumDefinition factory function for _EnumDefinition
func NewEnumDefinition(fields []EnumField) *_EnumDefinition {
	_result := &_EnumDefinition{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		Fields:                            fields,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// EnumDefinitionBuilder is a builder for EnumDefinition
type EnumDefinitionBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(fields []EnumField) EnumDefinitionBuilder
	// WithFields adds Fields (property field)
	WithFields(...EnumField) EnumDefinitionBuilder
	// 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 EnumDefinition or returns an error if something is wrong
	Build() (EnumDefinition, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() EnumDefinition
}

// NewEnumDefinitionBuilder() creates a EnumDefinitionBuilder
func NewEnumDefinitionBuilder() EnumDefinitionBuilder {
	return &_EnumDefinitionBuilder{_EnumDefinition: new(_EnumDefinition)}
}

type _EnumDefinitionBuilder struct {
	*_EnumDefinition

	parentBuilder *_ExtensionObjectDefinitionBuilder

	err *utils.MultiError
}

var _ (EnumDefinitionBuilder) = (*_EnumDefinitionBuilder)(nil)

func (b *_EnumDefinitionBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._EnumDefinition
}

func (b *_EnumDefinitionBuilder) WithMandatoryFields(fields []EnumField) EnumDefinitionBuilder {
	return b.WithFields(fields...)
}

func (b *_EnumDefinitionBuilder) WithFields(fields ...EnumField) EnumDefinitionBuilder {
	b.Fields = fields
	return b
}

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

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

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

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

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

// CreateEnumDefinitionBuilder creates a EnumDefinitionBuilder
func (b *_EnumDefinition) CreateEnumDefinitionBuilder() EnumDefinitionBuilder {
	if b == nil {
		return NewEnumDefinitionBuilder()
	}
	return &_EnumDefinitionBuilder{_EnumDefinition: b.deepCopy()}
}

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

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

func (m *_EnumDefinition) GetExtensionId() int32 {
	return int32(102)
}

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

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

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

func (m *_EnumDefinition) GetFields() []EnumField {
	return m.Fields
}

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

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

func (m *_EnumDefinition) GetTypeName() string {
	return "EnumDefinition"
}

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

	// Implicit Field (noOfFields)
	lengthInBits += 32

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

	return lengthInBits
}

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

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

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

	fields, err := ReadCountArrayField[EnumField](ctx, "fields", ReadComplex[EnumField](ExtensionObjectDefinitionParseWithBufferProducer[EnumField]((int32)(int32(104))), readBuffer), uint64(noOfFields))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'fields' field"))
	}
	m.Fields = fields

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

	return m, nil
}

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

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

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

func (m *_EnumDefinition) IsEnumDefinition() {}

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

func (m *_EnumDefinition) deepCopy() *_EnumDefinition {
	if m == nil {
		return nil
	}
	_EnumDefinitionCopy := &_EnumDefinition{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopySlice[EnumField, EnumField](m.Fields),
	}
	_EnumDefinitionCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _EnumDefinitionCopy
}

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