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

// RequestObsolete is the corresponding interface of RequestObsolete
// TODO: we should check if we are in basic mode
type RequestObsolete interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	Request
	// GetCalData returns CalData (property field)
	GetCalData() CALData
	// GetAlpha returns Alpha (property field)
	GetAlpha() Alpha
	// GetCalDataDecoded returns CalDataDecoded (virtual field)
	GetCalDataDecoded() CALData
	// IsRequestObsolete is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsRequestObsolete()
	// CreateBuilder creates a RequestObsoleteBuilder
	CreateRequestObsoleteBuilder() RequestObsoleteBuilder
}

// _RequestObsolete is the data-structure of this message
type _RequestObsolete struct {
	RequestContract
	CalData CALData
	Alpha   Alpha
}

var _ RequestObsolete = (*_RequestObsolete)(nil)
var _ RequestRequirements = (*_RequestObsolete)(nil)

// NewRequestObsolete factory function for _RequestObsolete
func NewRequestObsolete(peekedByte RequestType, startingCR *RequestType, resetMode *RequestType, secondPeek RequestType, termination RequestTermination, calData CALData, alpha Alpha) *_RequestObsolete {
	_result := &_RequestObsolete{
		RequestContract: NewRequest(peekedByte, startingCR, resetMode, secondPeek, termination),
		CalData:         calData,
		Alpha:           alpha,
	}
	_result.RequestContract.(*_Request)._SubType = _result
	return _result
}

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

// RequestObsoleteBuilder is a builder for RequestObsolete
type RequestObsoleteBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(calData CALData) RequestObsoleteBuilder
	// WithCalData adds CalData (property field)
	WithCalData(CALData) RequestObsoleteBuilder
	// WithCalDataBuilder adds CalData (property field) which is build by the builder
	WithCalDataBuilder(func(CALDataBuilder) CALDataBuilder) RequestObsoleteBuilder
	// WithAlpha adds Alpha (property field)
	WithOptionalAlpha(Alpha) RequestObsoleteBuilder
	// WithOptionalAlphaBuilder adds Alpha (property field) which is build by the builder
	WithOptionalAlphaBuilder(func(AlphaBuilder) AlphaBuilder) RequestObsoleteBuilder
	// Done is used to finish work on this child and return (or create one if none) to the parent builder
	Done() RequestBuilder
	// Build builds the RequestObsolete or returns an error if something is wrong
	Build() (RequestObsolete, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() RequestObsolete
}

// NewRequestObsoleteBuilder() creates a RequestObsoleteBuilder
func NewRequestObsoleteBuilder() RequestObsoleteBuilder {
	return &_RequestObsoleteBuilder{_RequestObsolete: new(_RequestObsolete)}
}

type _RequestObsoleteBuilder struct {
	*_RequestObsolete

	parentBuilder *_RequestBuilder

	collectedErr []error
}

var _ (RequestObsoleteBuilder) = (*_RequestObsoleteBuilder)(nil)

func (b *_RequestObsoleteBuilder) setParent(contract RequestContract) {
	b.RequestContract = contract
	contract.(*_Request)._SubType = b._RequestObsolete
}

func (b *_RequestObsoleteBuilder) WithMandatoryFields(calData CALData) RequestObsoleteBuilder {
	return b.WithCalData(calData)
}

func (b *_RequestObsoleteBuilder) WithCalData(calData CALData) RequestObsoleteBuilder {
	b.CalData = calData
	return b
}

func (b *_RequestObsoleteBuilder) WithCalDataBuilder(builderSupplier func(CALDataBuilder) CALDataBuilder) RequestObsoleteBuilder {
	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 *_RequestObsoleteBuilder) WithOptionalAlpha(alpha Alpha) RequestObsoleteBuilder {
	b.Alpha = alpha
	return b
}

func (b *_RequestObsoleteBuilder) WithOptionalAlphaBuilder(builderSupplier func(AlphaBuilder) AlphaBuilder) RequestObsoleteBuilder {
	builder := builderSupplier(b.Alpha.CreateAlphaBuilder())
	var err error
	b.Alpha, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "AlphaBuilder failed"))
	}
	return b
}

func (b *_RequestObsoleteBuilder) Build() (RequestObsolete, 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._RequestObsolete.deepCopy(), nil
}

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

func (b *_RequestObsoleteBuilder) Done() RequestBuilder {
	if b.parentBuilder == nil {
		b.parentBuilder = NewRequestBuilder().(*_RequestBuilder)
	}
	return b.parentBuilder
}

func (b *_RequestObsoleteBuilder) buildForRequest() (Request, error) {
	return b.Build()
}

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

// CreateRequestObsoleteBuilder creates a RequestObsoleteBuilder
func (b *_RequestObsolete) CreateRequestObsoleteBuilder() RequestObsoleteBuilder {
	if b == nil {
		return NewRequestObsoleteBuilder()
	}
	return &_RequestObsoleteBuilder{_RequestObsolete: b.deepCopy()}
}

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

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

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

func (m *_RequestObsolete) GetParent() RequestContract {
	return m.RequestContract
}

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

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

func (m *_RequestObsolete) GetAlpha() Alpha {
	return m.Alpha
}

///////////////////////
///////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/////////////////////// Accessors for virtual fields.
///////////////////////

func (m *_RequestObsolete) GetCalDataDecoded() CALData {
	ctx := context.Background()
	_ = ctx
	alpha := m.GetAlpha()
	_ = alpha
	return CastCALData(m.GetCalData())
}

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

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

func (m *_RequestObsolete) GetTypeName() string {
	return "RequestObsolete"
}

func (m *_RequestObsolete) GetLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(m.RequestContract.(*_Request).getLengthInBits(ctx))

	// Manual Field (calData)
	lengthInBits += uint16(int32((int32(m.GetCalData().GetLengthInBytes(ctx)) * int32(int32(2)))) * int32(int32(8)))

	// A virtual field doesn't have any in- or output.

	// Optional Field (alpha)
	if m.Alpha != nil {
		lengthInBits += m.Alpha.GetLengthInBits(ctx)
	}

	return lengthInBits
}

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

func (m *_RequestObsolete) parse(ctx context.Context, readBuffer utils.ReadBuffer, parent *_Request, cBusOptions CBusOptions) (__requestObsolete RequestObsolete, err error) {
	m.RequestContract = parent
	parent._SubType = m
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("RequestObsolete"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for RequestObsolete")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

	calData, err := ReadManualField[CALData](ctx, "calData", readBuffer, EnsureType[CALData](ReadCALData(ctx, readBuffer)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'calData' field"))
	}
	m.CalData = calData

	calDataDecoded, err := ReadVirtualField[CALData](ctx, "calDataDecoded", (*CALData)(nil), calData)
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'calDataDecoded' field"))
	}
	_ = calDataDecoded

	var alpha Alpha
	_alpha, err := ReadOptionalField[Alpha](ctx, "alpha", ReadComplex[Alpha](AlphaParseWithBuffer, readBuffer), true)
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'alpha' field"))
	}
	if _alpha != nil {
		alpha = *_alpha
		m.Alpha = alpha
	}

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

	return m, nil
}

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

		if err := WriteManualField[CALData](ctx, "calData", func(ctx context.Context) error { return WriteCALData(ctx, writeBuffer, m.GetCalData()) }, writeBuffer); err != nil {
			return errors.Wrap(err, "Error serializing 'calData' field")
		}
		// Virtual field
		calDataDecoded := m.GetCalDataDecoded()
		_ = calDataDecoded
		if _calDataDecodedErr := writeBuffer.WriteVirtual(ctx, "calDataDecoded", m.GetCalDataDecoded()); _calDataDecodedErr != nil {
			return errors.Wrap(_calDataDecodedErr, "Error serializing 'calDataDecoded' field")
		}

		if err := WriteOptionalField[Alpha](ctx, "alpha", GetRef(m.GetAlpha()), WriteComplex[Alpha](writeBuffer), true); err != nil {
			return errors.Wrap(err, "Error serializing 'alpha' field")
		}

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

func (m *_RequestObsolete) IsRequestObsolete() {}

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

func (m *_RequestObsolete) deepCopy() *_RequestObsolete {
	if m == nil {
		return nil
	}
	_RequestObsoleteCopy := &_RequestObsolete{
		m.RequestContract.(*_Request).deepCopy(),
		utils.DeepCopy[CALData](m.CalData),
		utils.DeepCopy[Alpha](m.Alpha),
	}
	_RequestObsoleteCopy.RequestContract.(*_Request)._SubType = m
	return _RequestObsoleteCopy
}

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