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

// TargetVariablesDataType is the corresponding interface of TargetVariablesDataType
type TargetVariablesDataType interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetTargetVariables returns TargetVariables (property field)
	GetTargetVariables() []FieldTargetDataType
	// IsTargetVariablesDataType is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsTargetVariablesDataType()
	// CreateBuilder creates a TargetVariablesDataTypeBuilder
	CreateTargetVariablesDataTypeBuilder() TargetVariablesDataTypeBuilder
}

// _TargetVariablesDataType is the data-structure of this message
type _TargetVariablesDataType struct {
	ExtensionObjectDefinitionContract
	TargetVariables []FieldTargetDataType
}

var _ TargetVariablesDataType = (*_TargetVariablesDataType)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_TargetVariablesDataType)(nil)

// NewTargetVariablesDataType factory function for _TargetVariablesDataType
func NewTargetVariablesDataType(targetVariables []FieldTargetDataType) *_TargetVariablesDataType {
	_result := &_TargetVariablesDataType{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		TargetVariables:                   targetVariables,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

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

// NewTargetVariablesDataTypeBuilder() creates a TargetVariablesDataTypeBuilder
func NewTargetVariablesDataTypeBuilder() TargetVariablesDataTypeBuilder {
	return &_TargetVariablesDataTypeBuilder{_TargetVariablesDataType: new(_TargetVariablesDataType)}
}

type _TargetVariablesDataTypeBuilder struct {
	*_TargetVariablesDataType

	parentBuilder *_ExtensionObjectDefinitionBuilder

	err *utils.MultiError
}

var _ (TargetVariablesDataTypeBuilder) = (*_TargetVariablesDataTypeBuilder)(nil)

func (b *_TargetVariablesDataTypeBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._TargetVariablesDataType
}

func (b *_TargetVariablesDataTypeBuilder) WithMandatoryFields(targetVariables []FieldTargetDataType) TargetVariablesDataTypeBuilder {
	return b.WithTargetVariables(targetVariables...)
}

func (b *_TargetVariablesDataTypeBuilder) WithTargetVariables(targetVariables ...FieldTargetDataType) TargetVariablesDataTypeBuilder {
	b.TargetVariables = targetVariables
	return b
}

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

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

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

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

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

// CreateTargetVariablesDataTypeBuilder creates a TargetVariablesDataTypeBuilder
func (b *_TargetVariablesDataType) CreateTargetVariablesDataTypeBuilder() TargetVariablesDataTypeBuilder {
	if b == nil {
		return NewTargetVariablesDataTypeBuilder()
	}
	return &_TargetVariablesDataTypeBuilder{_TargetVariablesDataType: b.deepCopy()}
}

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

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

func (m *_TargetVariablesDataType) GetExtensionId() int32 {
	return int32(15633)
}

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

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

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

func (m *_TargetVariablesDataType) GetTargetVariables() []FieldTargetDataType {
	return m.TargetVariables
}

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

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

func (m *_TargetVariablesDataType) GetTypeName() string {
	return "TargetVariablesDataType"
}

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

	// Implicit Field (noOfTargetVariables)
	lengthInBits += 32

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

	return lengthInBits
}

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

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

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

	targetVariables, err := ReadCountArrayField[FieldTargetDataType](ctx, "targetVariables", ReadComplex[FieldTargetDataType](ExtensionObjectDefinitionParseWithBufferProducer[FieldTargetDataType]((int32)(int32(14746))), readBuffer), uint64(noOfTargetVariables))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'targetVariables' field"))
	}
	m.TargetVariables = targetVariables

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

	return m, nil
}

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

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

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

func (m *_TargetVariablesDataType) IsTargetVariablesDataType() {}

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

func (m *_TargetVariablesDataType) deepCopy() *_TargetVariablesDataType {
	if m == nil {
		return nil
	}
	_TargetVariablesDataTypeCopy := &_TargetVariablesDataType{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopySlice[FieldTargetDataType, FieldTargetDataType](m.TargetVariables),
	}
	_TargetVariablesDataTypeCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _TargetVariablesDataTypeCopy
}

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