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

// CALReply is the corresponding interface of CALReply
type CALReply interface {
	CALReplyContract
	CALReplyRequirements
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	// IsCALReply is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsCALReply()
	// CreateBuilder creates a CALReplyBuilder
	CreateCALReplyBuilder() CALReplyBuilder
}

// CALReplyContract provides a set of functions which can be overwritten by a sub struct
type CALReplyContract interface {
	// GetCalType returns CalType (property field)
	GetCalType() byte
	// GetCalData returns CalData (property field)
	GetCalData() CALData
	// IsCALReply is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsCALReply()
	// CreateBuilder creates a CALReplyBuilder
	CreateCALReplyBuilder() CALReplyBuilder
}

// CALReplyRequirements provides a set of functions which need to be implemented by a sub struct
type CALReplyRequirements interface {
	GetLengthInBits(ctx context.Context) uint16
	GetLengthInBytes(ctx context.Context) uint16
	// GetCalType returns CalType (discriminator field)
	GetCalType() byte
}

// _CALReply is the data-structure of this message
type _CALReply struct {
	_SubType interface {
		CALReplyContract
		CALReplyRequirements
	}
	CalType byte
	CalData CALData
}

var _ CALReplyContract = (*_CALReply)(nil)

// NewCALReply factory function for _CALReply
func NewCALReply(calType byte, calData CALData) *_CALReply {
	if calData == nil {
		panic("calData of type CALData for CALReply must not be nil")
	}
	return &_CALReply{CalType: calType, CalData: calData}
}

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

// CALReplyBuilder is a builder for CALReply
type CALReplyBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(calType byte, calData CALData) CALReplyBuilder
	// WithCalType adds CalType (property field)
	WithCalType(byte) CALReplyBuilder
	// WithCalData adds CalData (property field)
	WithCalData(CALData) CALReplyBuilder
	// WithCalDataBuilder adds CalData (property field) which is build by the builder
	WithCalDataBuilder(func(CALDataBuilder) CALDataBuilder) CALReplyBuilder
	// AsCALReplyLong converts this build to a subType of CALReply. It is always possible to return to current builder using Done()
	AsCALReplyLong() CALReplyLongBuilder
	// AsCALReplyShort converts this build to a subType of CALReply. It is always possible to return to current builder using Done()
	AsCALReplyShort() CALReplyShortBuilder
	// Build builds the CALReply or returns an error if something is wrong
	PartialBuild() (CALReplyContract, error)
	// MustBuild does the same as Build but panics on error
	PartialMustBuild() CALReplyContract
	// Build builds the CALReply or returns an error if something is wrong
	Build() (CALReply, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() CALReply
}

// NewCALReplyBuilder() creates a CALReplyBuilder
func NewCALReplyBuilder() CALReplyBuilder {
	return &_CALReplyBuilder{_CALReply: new(_CALReply)}
}

type _CALReplyChildBuilder interface {
	utils.Copyable
	setParent(CALReplyContract)
	buildForCALReply() (CALReply, error)
}

type _CALReplyBuilder struct {
	*_CALReply

	childBuilder _CALReplyChildBuilder

	collectedErr []error
}

var _ (CALReplyBuilder) = (*_CALReplyBuilder)(nil)

func (b *_CALReplyBuilder) WithMandatoryFields(calType byte, calData CALData) CALReplyBuilder {
	return b.WithCalType(calType).WithCalData(calData)
}

func (b *_CALReplyBuilder) WithCalType(calType byte) CALReplyBuilder {
	b.CalType = calType
	return b
}

func (b *_CALReplyBuilder) WithCalData(calData CALData) CALReplyBuilder {
	b.CalData = calData
	return b
}

func (b *_CALReplyBuilder) WithCalDataBuilder(builderSupplier func(CALDataBuilder) CALDataBuilder) CALReplyBuilder {
	builder := builderSupplier(b.CalData.CreateCALDataBuilder())
	var err error
	b.CalData, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "CALDataBuilder failed"))
	}
	return b
}

func (b *_CALReplyBuilder) PartialBuild() (CALReplyContract, error) {
	if b.CalData == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'calData' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._CALReply.deepCopy(), nil
}

func (b *_CALReplyBuilder) PartialMustBuild() CALReplyContract {
	build, err := b.PartialBuild()
	if err != nil {
		panic(err)
	}
	return build
}

func (b *_CALReplyBuilder) AsCALReplyLong() CALReplyLongBuilder {
	if cb, ok := b.childBuilder.(CALReplyLongBuilder); ok {
		return cb
	}
	cb := NewCALReplyLongBuilder().(*_CALReplyLongBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_CALReplyBuilder) AsCALReplyShort() CALReplyShortBuilder {
	if cb, ok := b.childBuilder.(CALReplyShortBuilder); ok {
		return cb
	}
	cb := NewCALReplyShortBuilder().(*_CALReplyShortBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_CALReplyBuilder) Build() (CALReply, error) {
	v, err := b.PartialBuild()
	if err != nil {
		return nil, errors.Wrap(err, "error occurred during partial build")
	}
	if b.childBuilder == nil {
		return nil, errors.New("no child builder present")
	}
	b.childBuilder.setParent(v)
	return b.childBuilder.buildForCALReply()
}

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

func (b *_CALReplyBuilder) DeepCopy() any {
	_copy := b.CreateCALReplyBuilder().(*_CALReplyBuilder)
	_copy.childBuilder = b.childBuilder.DeepCopy().(_CALReplyChildBuilder)
	_copy.childBuilder.setParent(_copy)
	if b.collectedErr != nil {
		copy(_copy.collectedErr, b.collectedErr)
	}
	return _copy
}

// CreateCALReplyBuilder creates a CALReplyBuilder
func (b *_CALReply) CreateCALReplyBuilder() CALReplyBuilder {
	if b == nil {
		return NewCALReplyBuilder()
	}
	return &_CALReplyBuilder{_CALReply: b.deepCopy()}
}

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

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

func (m *_CALReply) GetCalType() byte {
	return m.CalType
}

func (m *_CALReply) GetCalData() CALData {
	return m.CalData
}

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

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

func (m *_CALReply) GetTypeName() string {
	return "CALReply"
}

func (m *_CALReply) getLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(0)

	// Simple field (calData)
	lengthInBits += m.CalData.GetLengthInBits(ctx)

	return lengthInBits
}

func (m *_CALReply) GetLengthInBits(ctx context.Context) uint16 {
	return m._SubType.GetLengthInBits(ctx)
}

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

func CALReplyParse[T CALReply](ctx context.Context, theBytes []byte, cBusOptions CBusOptions, requestContext RequestContext) (T, error) {
	return CALReplyParseWithBuffer[T](ctx, utils.NewReadBufferByteBased(theBytes), cBusOptions, requestContext)
}

func CALReplyParseWithBufferProducer[T CALReply](cBusOptions CBusOptions, requestContext RequestContext) func(ctx context.Context, readBuffer utils.ReadBuffer) (T, error) {
	return func(ctx context.Context, readBuffer utils.ReadBuffer) (T, error) {
		v, err := CALReplyParseWithBuffer[T](ctx, readBuffer, cBusOptions, requestContext)
		if err != nil {
			var zero T
			return zero, err
		}
		return v, nil
	}
}

func CALReplyParseWithBuffer[T CALReply](ctx context.Context, readBuffer utils.ReadBuffer, cBusOptions CBusOptions, requestContext RequestContext) (T, error) {
	v, err := (new(_CALReply)).parse(ctx, readBuffer, cBusOptions, requestContext)
	if err != nil {
		var zero T
		return zero, err
	}
	vc, ok := v.(T)
	if !ok {
		var zero T
		return zero, errors.Errorf("Unexpected type %T. Expected type %T", v, *new(T))
	}
	return vc, nil
}

func (m *_CALReply) parse(ctx context.Context, readBuffer utils.ReadBuffer, cBusOptions CBusOptions, requestContext RequestContext) (__cALReply CALReply, err error) {
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("CALReply"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for CALReply")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

	calType, err := ReadPeekField[byte](ctx, "calType", ReadByte(readBuffer, 8), 0)
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'calType' field"))
	}
	m.CalType = calType

	// Switch Field (Depending on the discriminator values, passes the instantiation to a sub-type)
	var _child CALReply
	switch {
	case calType == 0x86: // CALReplyLong
		if _child, err = new(_CALReplyLong).parse(ctx, readBuffer, m, cBusOptions, requestContext); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type CALReplyLong for type-switch of CALReply")
		}
	case true: // CALReplyShort
		if _child, err = new(_CALReplyShort).parse(ctx, readBuffer, m, cBusOptions, requestContext); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type CALReplyShort for type-switch of CALReply")
		}
	default:
		return nil, errors.Errorf("Unmapped type for parameters [calType=%v]", calType)
	}

	calData, err := ReadSimpleField[CALData](ctx, "calData", ReadComplex[CALData](CALDataParseWithBufferProducer[CALData]((RequestContext)(requestContext)), readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'calData' field"))
	}
	m.CalData = calData

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

	return _child, nil
}

func (pm *_CALReply) serializeParent(ctx context.Context, writeBuffer utils.WriteBuffer, child CALReply, serializeChildFunction func() error) error {
	// We redirect all calls through client as some methods are only implemented there
	m := child
	_ = m
	positionAware := writeBuffer
	_ = positionAware
	log := zerolog.Ctx(ctx)
	_ = log
	if pushErr := writeBuffer.PushContext("CALReply"); pushErr != nil {
		return errors.Wrap(pushErr, "Error pushing for CALReply")
	}

	// Switch field (Depending on the discriminator values, passes the serialization to a sub-type)
	if _typeSwitchErr := serializeChildFunction(); _typeSwitchErr != nil {
		return errors.Wrap(_typeSwitchErr, "Error serializing sub-type field")
	}

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

	if popErr := writeBuffer.PopContext("CALReply"); popErr != nil {
		return errors.Wrap(popErr, "Error popping for CALReply")
	}
	return nil
}

func (m *_CALReply) IsCALReply() {}

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

func (m *_CALReply) deepCopy() *_CALReply {
	if m == nil {
		return nil
	}
	_CALReplyCopy := &_CALReply{
		nil, // will be set by child
		m.CalType,
		utils.DeepCopy[CALData](m.CalData),
	}
	return _CALReplyCopy
}
