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

// EnumField is the corresponding interface of EnumField
type EnumField interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetValue returns Value (property field)
	GetValue() int64
	// GetDisplayName returns DisplayName (property field)
	GetDisplayName() LocalizedText
	// GetDescription returns Description (property field)
	GetDescription() LocalizedText
	// GetName returns Name (property field)
	GetName() PascalString
	// IsEnumField is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsEnumField()
	// CreateBuilder creates a EnumFieldBuilder
	CreateEnumFieldBuilder() EnumFieldBuilder
}

// _EnumField is the data-structure of this message
type _EnumField struct {
	ExtensionObjectDefinitionContract
	Value       int64
	DisplayName LocalizedText
	Description LocalizedText
	Name        PascalString
}

var _ EnumField = (*_EnumField)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_EnumField)(nil)

// NewEnumField factory function for _EnumField
func NewEnumField(value int64, displayName LocalizedText, description LocalizedText, name PascalString) *_EnumField {
	if displayName == nil {
		panic("displayName of type LocalizedText for EnumField must not be nil")
	}
	if description == nil {
		panic("description of type LocalizedText for EnumField must not be nil")
	}
	if name == nil {
		panic("name of type PascalString for EnumField must not be nil")
	}
	_result := &_EnumField{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		Value:                             value,
		DisplayName:                       displayName,
		Description:                       description,
		Name:                              name,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// EnumFieldBuilder is a builder for EnumField
type EnumFieldBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(value int64, displayName LocalizedText, description LocalizedText, name PascalString) EnumFieldBuilder
	// WithValue adds Value (property field)
	WithValue(int64) EnumFieldBuilder
	// WithDisplayName adds DisplayName (property field)
	WithDisplayName(LocalizedText) EnumFieldBuilder
	// WithDisplayNameBuilder adds DisplayName (property field) which is build by the builder
	WithDisplayNameBuilder(func(LocalizedTextBuilder) LocalizedTextBuilder) EnumFieldBuilder
	// WithDescription adds Description (property field)
	WithDescription(LocalizedText) EnumFieldBuilder
	// WithDescriptionBuilder adds Description (property field) which is build by the builder
	WithDescriptionBuilder(func(LocalizedTextBuilder) LocalizedTextBuilder) EnumFieldBuilder
	// WithName adds Name (property field)
	WithName(PascalString) EnumFieldBuilder
	// WithNameBuilder adds Name (property field) which is build by the builder
	WithNameBuilder(func(PascalStringBuilder) PascalStringBuilder) EnumFieldBuilder
	// 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 EnumField or returns an error if something is wrong
	Build() (EnumField, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() EnumField
}

// NewEnumFieldBuilder() creates a EnumFieldBuilder
func NewEnumFieldBuilder() EnumFieldBuilder {
	return &_EnumFieldBuilder{_EnumField: new(_EnumField)}
}

type _EnumFieldBuilder struct {
	*_EnumField

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (EnumFieldBuilder) = (*_EnumFieldBuilder)(nil)

func (b *_EnumFieldBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._EnumField
}

func (b *_EnumFieldBuilder) WithMandatoryFields(value int64, displayName LocalizedText, description LocalizedText, name PascalString) EnumFieldBuilder {
	return b.WithValue(value).WithDisplayName(displayName).WithDescription(description).WithName(name)
}

func (b *_EnumFieldBuilder) WithValue(value int64) EnumFieldBuilder {
	b.Value = value
	return b
}

func (b *_EnumFieldBuilder) WithDisplayName(displayName LocalizedText) EnumFieldBuilder {
	b.DisplayName = displayName
	return b
}

func (b *_EnumFieldBuilder) WithDisplayNameBuilder(builderSupplier func(LocalizedTextBuilder) LocalizedTextBuilder) EnumFieldBuilder {
	builder := builderSupplier(b.DisplayName.CreateLocalizedTextBuilder())
	var err error
	b.DisplayName, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "LocalizedTextBuilder failed"))
	}
	return b
}

func (b *_EnumFieldBuilder) WithDescription(description LocalizedText) EnumFieldBuilder {
	b.Description = description
	return b
}

func (b *_EnumFieldBuilder) WithDescriptionBuilder(builderSupplier func(LocalizedTextBuilder) LocalizedTextBuilder) EnumFieldBuilder {
	builder := builderSupplier(b.Description.CreateLocalizedTextBuilder())
	var err error
	b.Description, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "LocalizedTextBuilder failed"))
	}
	return b
}

func (b *_EnumFieldBuilder) WithName(name PascalString) EnumFieldBuilder {
	b.Name = name
	return b
}

func (b *_EnumFieldBuilder) WithNameBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) EnumFieldBuilder {
	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 *_EnumFieldBuilder) Build() (EnumField, error) {
	if b.DisplayName == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'displayName' not set"))
	}
	if b.Description == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'description' not set"))
	}
	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._EnumField.deepCopy(), nil
}

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

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

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

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

// CreateEnumFieldBuilder creates a EnumFieldBuilder
func (b *_EnumField) CreateEnumFieldBuilder() EnumFieldBuilder {
	if b == nil {
		return NewEnumFieldBuilder()
	}
	return &_EnumFieldBuilder{_EnumField: b.deepCopy()}
}

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

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

func (m *_EnumField) GetExtensionId() int32 {
	return int32(104)
}

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

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

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

func (m *_EnumField) GetValue() int64 {
	return m.Value
}

func (m *_EnumField) GetDisplayName() LocalizedText {
	return m.DisplayName
}

func (m *_EnumField) GetDescription() LocalizedText {
	return m.Description
}

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

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

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

func (m *_EnumField) GetTypeName() string {
	return "EnumField"
}

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

	// Simple field (value)
	lengthInBits += 64

	// Simple field (displayName)
	lengthInBits += m.DisplayName.GetLengthInBits(ctx)

	// Simple field (description)
	lengthInBits += m.Description.GetLengthInBits(ctx)

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

	return lengthInBits
}

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

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

	value, err := ReadSimpleField(ctx, "value", ReadSignedLong(readBuffer, uint8(64)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'value' field"))
	}
	m.Value = value

	displayName, err := ReadSimpleField[LocalizedText](ctx, "displayName", ReadComplex[LocalizedText](LocalizedTextParseWithBuffer, readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'displayName' field"))
	}
	m.DisplayName = displayName

	description, err := ReadSimpleField[LocalizedText](ctx, "description", ReadComplex[LocalizedText](LocalizedTextParseWithBuffer, readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'description' field"))
	}
	m.Description = description

	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("EnumField"); closeErr != nil {
		return nil, errors.Wrap(closeErr, "Error closing for EnumField")
	}

	return m, nil
}

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

		if err := WriteSimpleField[int64](ctx, "value", m.GetValue(), WriteSignedLong(writeBuffer, 64)); err != nil {
			return errors.Wrap(err, "Error serializing 'value' field")
		}

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

		if err := WriteSimpleField[LocalizedText](ctx, "description", m.GetDescription(), WriteComplex[LocalizedText](writeBuffer)); err != nil {
			return errors.Wrap(err, "Error serializing 'description' 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("EnumField"); popErr != nil {
			return errors.Wrap(popErr, "Error popping for EnumField")
		}
		return nil
	}
	return m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).serializeParent(ctx, writeBuffer, m, ser)
}

func (m *_EnumField) IsEnumField() {}

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

func (m *_EnumField) deepCopy() *_EnumField {
	if m == nil {
		return nil
	}
	_EnumFieldCopy := &_EnumField{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		m.Value,
		utils.DeepCopy[LocalizedText](m.DisplayName),
		utils.DeepCopy[LocalizedText](m.Description),
		utils.DeepCopy[PascalString](m.Name),
	}
	_EnumFieldCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _EnumFieldCopy
}

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