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

// VariantDouble is the corresponding interface of VariantDouble
type VariantDouble interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	Variant
	// GetArrayLength returns ArrayLength (property field)
	GetArrayLength() *int32
	// GetValue returns Value (property field)
	GetValue() []float64
	// IsVariantDouble is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsVariantDouble()
	// CreateBuilder creates a VariantDoubleBuilder
	CreateVariantDoubleBuilder() VariantDoubleBuilder
}

// _VariantDouble is the data-structure of this message
type _VariantDouble struct {
	VariantContract
	ArrayLength *int32
	Value       []float64
}

var _ VariantDouble = (*_VariantDouble)(nil)
var _ VariantRequirements = (*_VariantDouble)(nil)

// NewVariantDouble factory function for _VariantDouble
func NewVariantDouble(arrayLengthSpecified bool, arrayDimensionsSpecified bool, noOfArrayDimensions *int32, arrayDimensions []bool, arrayLength *int32, value []float64) *_VariantDouble {
	_result := &_VariantDouble{
		VariantContract: NewVariant(arrayLengthSpecified, arrayDimensionsSpecified, noOfArrayDimensions, arrayDimensions),
		ArrayLength:     arrayLength,
		Value:           value,
	}
	_result.VariantContract.(*_Variant)._SubType = _result
	return _result
}

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

// VariantDoubleBuilder is a builder for VariantDouble
type VariantDoubleBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(value []float64) VariantDoubleBuilder
	// WithArrayLength adds ArrayLength (property field)
	WithOptionalArrayLength(int32) VariantDoubleBuilder
	// WithValue adds Value (property field)
	WithValue(...float64) VariantDoubleBuilder
	// Done is used to finish work on this child and return (or create one if none) to the parent builder
	Done() VariantBuilder
	// Build builds the VariantDouble or returns an error if something is wrong
	Build() (VariantDouble, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() VariantDouble
}

// NewVariantDoubleBuilder() creates a VariantDoubleBuilder
func NewVariantDoubleBuilder() VariantDoubleBuilder {
	return &_VariantDoubleBuilder{_VariantDouble: new(_VariantDouble)}
}

type _VariantDoubleBuilder struct {
	*_VariantDouble

	parentBuilder *_VariantBuilder

	err *utils.MultiError
}

var _ (VariantDoubleBuilder) = (*_VariantDoubleBuilder)(nil)

func (b *_VariantDoubleBuilder) setParent(contract VariantContract) {
	b.VariantContract = contract
	contract.(*_Variant)._SubType = b._VariantDouble
}

func (b *_VariantDoubleBuilder) WithMandatoryFields(value []float64) VariantDoubleBuilder {
	return b.WithValue(value...)
}

func (b *_VariantDoubleBuilder) WithOptionalArrayLength(arrayLength int32) VariantDoubleBuilder {
	b.ArrayLength = &arrayLength
	return b
}

func (b *_VariantDoubleBuilder) WithValue(value ...float64) VariantDoubleBuilder {
	b.Value = value
	return b
}

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

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

func (b *_VariantDoubleBuilder) Done() VariantBuilder {
	if b.parentBuilder == nil {
		b.parentBuilder = NewVariantBuilder().(*_VariantBuilder)
	}
	return b.parentBuilder
}

func (b *_VariantDoubleBuilder) buildForVariant() (Variant, error) {
	return b.Build()
}

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

// CreateVariantDoubleBuilder creates a VariantDoubleBuilder
func (b *_VariantDouble) CreateVariantDoubleBuilder() VariantDoubleBuilder {
	if b == nil {
		return NewVariantDoubleBuilder()
	}
	return &_VariantDoubleBuilder{_VariantDouble: b.deepCopy()}
}

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

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

func (m *_VariantDouble) GetVariantType() uint8 {
	return uint8(11)
}

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

func (m *_VariantDouble) GetParent() VariantContract {
	return m.VariantContract
}

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

func (m *_VariantDouble) GetArrayLength() *int32 {
	return m.ArrayLength
}

func (m *_VariantDouble) GetValue() []float64 {
	return m.Value
}

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

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

func (m *_VariantDouble) GetTypeName() string {
	return "VariantDouble"
}

func (m *_VariantDouble) GetLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(m.VariantContract.(*_Variant).getLengthInBits(ctx))

	// Optional Field (arrayLength)
	if m.ArrayLength != nil {
		lengthInBits += 32
	}

	// Array field
	if len(m.Value) > 0 {
		lengthInBits += 64 * uint16(len(m.Value))
	}

	return lengthInBits
}

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

func (m *_VariantDouble) parse(ctx context.Context, readBuffer utils.ReadBuffer, parent *_Variant, arrayLengthSpecified bool) (__variantDouble VariantDouble, err error) {
	m.VariantContract = parent
	parent._SubType = m
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("VariantDouble"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for VariantDouble")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

	var arrayLength *int32
	arrayLength, err = ReadOptionalField[int32](ctx, "arrayLength", ReadSignedInt(readBuffer, uint8(32)), arrayLengthSpecified)
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'arrayLength' field"))
	}
	m.ArrayLength = arrayLength

	value, err := ReadCountArrayField[float64](ctx, "value", ReadDouble(readBuffer, uint8(64)), uint64(utils.InlineIf(bool((arrayLength) == (nil)), func() any { return int32(int32(1)) }, func() any { return int32((*arrayLength)) }).(int32)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'value' field"))
	}
	m.Value = value

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

	return m, nil
}

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

		if err := WriteOptionalField[int32](ctx, "arrayLength", m.GetArrayLength(), WriteSignedInt(writeBuffer, 32), true); err != nil {
			return errors.Wrap(err, "Error serializing 'arrayLength' field")
		}

		if err := WriteSimpleTypeArrayField(ctx, "value", m.GetValue(), WriteDouble(writeBuffer, 64)); err != nil {
			return errors.Wrap(err, "Error serializing 'value' field")
		}

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

func (m *_VariantDouble) IsVariantDouble() {}

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

func (m *_VariantDouble) deepCopy() *_VariantDouble {
	if m == nil {
		return nil
	}
	_VariantDoubleCopy := &_VariantDouble{
		m.VariantContract.(*_Variant).deepCopy(),
		utils.CopyPtr[int32](m.ArrayLength),
		utils.DeepCopySlice[float64, float64](m.Value),
	}
	_VariantDoubleCopy.VariantContract.(*_Variant)._SubType = m
	return _VariantDoubleCopy
}

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