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

// CALDataReply is the corresponding interface of CALDataReply
type CALDataReply interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	CALData
	// GetParamNo returns ParamNo (property field)
	// Reply
	GetParamNo() Parameter
	// GetParameterValue returns ParameterValue (property field)
	GetParameterValue() ParameterValue
	// IsCALDataReply is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsCALDataReply()
	// CreateBuilder creates a CALDataReplyBuilder
	CreateCALDataReplyBuilder() CALDataReplyBuilder
}

// _CALDataReply is the data-structure of this message
type _CALDataReply struct {
	CALDataContract
	ParamNo        Parameter
	ParameterValue ParameterValue
}

var _ CALDataReply = (*_CALDataReply)(nil)
var _ CALDataRequirements = (*_CALDataReply)(nil)

// NewCALDataReply factory function for _CALDataReply
func NewCALDataReply(requestContext RequestContext, commandTypeContainer CALCommandTypeContainer, additionalData CALData, paramNo Parameter, parameterValue ParameterValue) *_CALDataReply {
	if parameterValue == nil {
		panic("parameterValue of type ParameterValue for CALDataReply must not be nil")
	}
	_result := &_CALDataReply{
		CALDataContract: NewCALData(requestContext, commandTypeContainer, additionalData),
		ParamNo:         paramNo,
		ParameterValue:  parameterValue,
	}
	_result.CALDataContract.(*_CALData)._SubType = _result
	return _result
}

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

// CALDataReplyBuilder is a builder for CALDataReply
type CALDataReplyBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(paramNo Parameter, parameterValue ParameterValue) CALDataReplyBuilder
	// WithParamNo adds ParamNo (property field)
	WithParamNo(Parameter) CALDataReplyBuilder
	// WithParameterValue adds ParameterValue (property field)
	WithParameterValue(ParameterValue) CALDataReplyBuilder
	// WithParameterValueBuilder adds ParameterValue (property field) which is build by the builder
	WithParameterValueBuilder(func(ParameterValueBuilder) ParameterValueBuilder) CALDataReplyBuilder
	// Done is used to finish work on this child and return (or create one if none) to the parent builder
	Done() CALDataBuilder
	// Build builds the CALDataReply or returns an error if something is wrong
	Build() (CALDataReply, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() CALDataReply
}

// NewCALDataReplyBuilder() creates a CALDataReplyBuilder
func NewCALDataReplyBuilder() CALDataReplyBuilder {
	return &_CALDataReplyBuilder{_CALDataReply: new(_CALDataReply)}
}

type _CALDataReplyBuilder struct {
	*_CALDataReply

	parentBuilder *_CALDataBuilder

	collectedErr []error
}

var _ (CALDataReplyBuilder) = (*_CALDataReplyBuilder)(nil)

func (b *_CALDataReplyBuilder) setParent(contract CALDataContract) {
	b.CALDataContract = contract
	contract.(*_CALData)._SubType = b._CALDataReply
}

func (b *_CALDataReplyBuilder) WithMandatoryFields(paramNo Parameter, parameterValue ParameterValue) CALDataReplyBuilder {
	return b.WithParamNo(paramNo).WithParameterValue(parameterValue)
}

func (b *_CALDataReplyBuilder) WithParamNo(paramNo Parameter) CALDataReplyBuilder {
	b.ParamNo = paramNo
	return b
}

func (b *_CALDataReplyBuilder) WithParameterValue(parameterValue ParameterValue) CALDataReplyBuilder {
	b.ParameterValue = parameterValue
	return b
}

func (b *_CALDataReplyBuilder) WithParameterValueBuilder(builderSupplier func(ParameterValueBuilder) ParameterValueBuilder) CALDataReplyBuilder {
	builder := builderSupplier(b.ParameterValue.CreateParameterValueBuilder())
	var err error
	b.ParameterValue, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "ParameterValueBuilder failed"))
	}
	return b
}

func (b *_CALDataReplyBuilder) Build() (CALDataReply, error) {
	if b.ParameterValue == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'parameterValue' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._CALDataReply.deepCopy(), nil
}

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

func (b *_CALDataReplyBuilder) Done() CALDataBuilder {
	if b.parentBuilder == nil {
		b.parentBuilder = NewCALDataBuilder().(*_CALDataBuilder)
	}
	return b.parentBuilder
}

func (b *_CALDataReplyBuilder) buildForCALData() (CALData, error) {
	return b.Build()
}

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

// CreateCALDataReplyBuilder creates a CALDataReplyBuilder
func (b *_CALDataReply) CreateCALDataReplyBuilder() CALDataReplyBuilder {
	if b == nil {
		return NewCALDataReplyBuilder()
	}
	return &_CALDataReplyBuilder{_CALDataReply: b.deepCopy()}
}

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

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

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

func (m *_CALDataReply) GetParent() CALDataContract {
	return m.CALDataContract
}

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

func (m *_CALDataReply) GetParamNo() Parameter {
	return m.ParamNo
}

func (m *_CALDataReply) GetParameterValue() ParameterValue {
	return m.ParameterValue
}

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

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

func (m *_CALDataReply) GetTypeName() string {
	return "CALDataReply"
}

func (m *_CALDataReply) GetLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(m.CALDataContract.(*_CALData).getLengthInBits(ctx))

	// Simple field (paramNo)
	lengthInBits += 8

	// Simple field (parameterValue)
	lengthInBits += m.ParameterValue.GetLengthInBits(ctx)

	return lengthInBits
}

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

func (m *_CALDataReply) parse(ctx context.Context, readBuffer utils.ReadBuffer, parent *_CALData, commandTypeContainer CALCommandTypeContainer, requestContext RequestContext) (__cALDataReply CALDataReply, err error) {
	m.CALDataContract = parent
	parent._SubType = m
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("CALDataReply"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for CALDataReply")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

	paramNo, err := ReadEnumField[Parameter](ctx, "paramNo", "Parameter", ReadEnum(ParameterByValue, ReadUnsignedByte(readBuffer, uint8(8))))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'paramNo' field"))
	}
	m.ParamNo = paramNo

	parameterValue, err := ReadSimpleField[ParameterValue](ctx, "parameterValue", ReadComplex[ParameterValue](ParameterValueParseWithBufferProducer[ParameterValue]((ParameterType)(paramNo.ParameterType()), (uint8)(uint8(commandTypeContainer.NumBytes())-uint8(uint8(1)))), readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'parameterValue' field"))
	}
	m.ParameterValue = parameterValue

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

	return m, nil
}

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

		if err := WriteSimpleEnumField[Parameter](ctx, "paramNo", "Parameter", m.GetParamNo(), WriteEnum[Parameter, uint8](Parameter.GetValue, Parameter.PLC4XEnumName, WriteUnsignedByte(writeBuffer, 8))); err != nil {
			return errors.Wrap(err, "Error serializing 'paramNo' field")
		}

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

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

func (m *_CALDataReply) IsCALDataReply() {}

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

func (m *_CALDataReply) deepCopy() *_CALDataReply {
	if m == nil {
		return nil
	}
	_CALDataReplyCopy := &_CALDataReply{
		m.CALDataContract.(*_CALData).deepCopy(),
		m.ParamNo,
		utils.DeepCopy[ParameterValue](m.ParameterValue),
	}
	_CALDataReplyCopy.CALDataContract.(*_CALData)._SubType = m
	return _CALDataReplyCopy
}

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