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

// Constant values.
const RequestCommand_INITIATOR byte = 0x5C

// RequestCommand is the corresponding interface of RequestCommand
type RequestCommand interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	Request
	// GetCBusOptions returns CBusOptions (property field)
	GetCBusOptions() CBusOptions
	// GetCbusCommand returns CbusCommand (property field)
	// 0x5C == "\"
	GetCbusCommand() CBusCommand
	// GetChksum returns Chksum (property field)
	GetChksum() Checksum
	// GetAlpha returns Alpha (property field)
	GetAlpha() Alpha
	// GetCbusCommandDecoded returns CbusCommandDecoded (virtual field)
	GetCbusCommandDecoded() CBusCommand
	// GetChksumDecoded returns ChksumDecoded (virtual field)
	GetChksumDecoded() Checksum
	// IsRequestCommand is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsRequestCommand()
	// CreateBuilder creates a RequestCommandBuilder
	CreateRequestCommandBuilder() RequestCommandBuilder
}

// _RequestCommand is the data-structure of this message
type _RequestCommand struct {
	RequestContract
	CBusOptions CBusOptions
	CbusCommand CBusCommand
	Chksum      Checksum
	Alpha       Alpha
}

var _ RequestCommand = (*_RequestCommand)(nil)
var _ RequestRequirements = (*_RequestCommand)(nil)

// NewRequestCommand factory function for _RequestCommand
func NewRequestCommand(peekedByte RequestType, startingCR *RequestType, resetMode *RequestType, secondPeek RequestType, termination RequestTermination, cBusOptions CBusOptions, cbusCommand CBusCommand, chksum Checksum, alpha Alpha) *_RequestCommand {
	_result := &_RequestCommand{
		RequestContract: NewRequest(peekedByte, startingCR, resetMode, secondPeek, termination),
		CBusOptions:     cBusOptions,
		CbusCommand:     cbusCommand,
		Chksum:          chksum,
		Alpha:           alpha,
	}
	_result.RequestContract.(*_Request)._SubType = _result
	return _result
}

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

// RequestCommandBuilder is a builder for RequestCommand
type RequestCommandBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(cBusOptions CBusOptions, cbusCommand CBusCommand, chksum Checksum) RequestCommandBuilder
	// WithCBusOptions adds CBusOptions (property field)
	WithCBusOptions(CBusOptions) RequestCommandBuilder
	// WithCBusOptionsBuilder adds CBusOptions (property field) which is build by the builder
	WithCBusOptionsBuilder(func(CBusOptionsBuilder) CBusOptionsBuilder) RequestCommandBuilder
	// WithCbusCommand adds CbusCommand (property field)
	WithCbusCommand(CBusCommand) RequestCommandBuilder
	// WithCbusCommandBuilder adds CbusCommand (property field) which is build by the builder
	WithCbusCommandBuilder(func(CBusCommandBuilder) CBusCommandBuilder) RequestCommandBuilder
	// WithChksum adds Chksum (property field)
	WithChksum(Checksum) RequestCommandBuilder
	// WithChksumBuilder adds Chksum (property field) which is build by the builder
	WithChksumBuilder(func(ChecksumBuilder) ChecksumBuilder) RequestCommandBuilder
	// WithAlpha adds Alpha (property field)
	WithOptionalAlpha(Alpha) RequestCommandBuilder
	// WithOptionalAlphaBuilder adds Alpha (property field) which is build by the builder
	WithOptionalAlphaBuilder(func(AlphaBuilder) AlphaBuilder) RequestCommandBuilder
	// 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 RequestCommand or returns an error if something is wrong
	Build() (RequestCommand, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() RequestCommand
}

// NewRequestCommandBuilder() creates a RequestCommandBuilder
func NewRequestCommandBuilder() RequestCommandBuilder {
	return &_RequestCommandBuilder{_RequestCommand: new(_RequestCommand)}
}

type _RequestCommandBuilder struct {
	*_RequestCommand

	parentBuilder *_RequestBuilder

	collectedErr []error
}

var _ (RequestCommandBuilder) = (*_RequestCommandBuilder)(nil)

func (b *_RequestCommandBuilder) setParent(contract RequestContract) {
	b.RequestContract = contract
	contract.(*_Request)._SubType = b._RequestCommand
}

func (b *_RequestCommandBuilder) WithMandatoryFields(cBusOptions CBusOptions, cbusCommand CBusCommand, chksum Checksum) RequestCommandBuilder {
	return b.WithCBusOptions(cBusOptions).WithCbusCommand(cbusCommand).WithChksum(chksum)
}

func (b *_RequestCommandBuilder) WithCBusOptions(cBusOptions CBusOptions) RequestCommandBuilder {
	b.CBusOptions = cBusOptions
	return b
}

func (b *_RequestCommandBuilder) WithCBusOptionsBuilder(builderSupplier func(CBusOptionsBuilder) CBusOptionsBuilder) RequestCommandBuilder {
	builder := builderSupplier(b.CBusOptions.CreateCBusOptionsBuilder())
	var err error
	b.CBusOptions, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "CBusOptionsBuilder failed"))
	}
	return b
}

func (b *_RequestCommandBuilder) WithCbusCommand(cbusCommand CBusCommand) RequestCommandBuilder {
	b.CbusCommand = cbusCommand
	return b
}

func (b *_RequestCommandBuilder) WithCbusCommandBuilder(builderSupplier func(CBusCommandBuilder) CBusCommandBuilder) RequestCommandBuilder {
	builder := builderSupplier(b.CbusCommand.CreateCBusCommandBuilder())
	var err error
	b.CbusCommand, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "CBusCommandBuilder failed"))
	}
	return b
}

func (b *_RequestCommandBuilder) WithChksum(chksum Checksum) RequestCommandBuilder {
	b.Chksum = chksum
	return b
}

func (b *_RequestCommandBuilder) WithChksumBuilder(builderSupplier func(ChecksumBuilder) ChecksumBuilder) RequestCommandBuilder {
	builder := builderSupplier(b.Chksum.CreateChecksumBuilder())
	var err error
	b.Chksum, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "ChecksumBuilder failed"))
	}
	return b
}

func (b *_RequestCommandBuilder) WithOptionalAlpha(alpha Alpha) RequestCommandBuilder {
	b.Alpha = alpha
	return b
}

func (b *_RequestCommandBuilder) WithOptionalAlphaBuilder(builderSupplier func(AlphaBuilder) AlphaBuilder) RequestCommandBuilder {
	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 *_RequestCommandBuilder) Build() (RequestCommand, error) {
	if b.CBusOptions == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'cBusOptions' not set"))
	}
	if b.CbusCommand == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'cbusCommand' not set"))
	}
	if b.Chksum == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'chksum' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._RequestCommand.deepCopy(), nil
}

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

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

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

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

// CreateRequestCommandBuilder creates a RequestCommandBuilder
func (b *_RequestCommand) CreateRequestCommandBuilder() RequestCommandBuilder {
	if b == nil {
		return NewRequestCommandBuilder()
	}
	return &_RequestCommandBuilder{_RequestCommand: b.deepCopy()}
}

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

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

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

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

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

func (m *_RequestCommand) GetCBusOptions() CBusOptions {
	return m.CBusOptions
}

func (m *_RequestCommand) GetCbusCommand() CBusCommand {
	return m.CbusCommand
}

func (m *_RequestCommand) GetChksum() Checksum {
	return m.Chksum
}

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

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

func (m *_RequestCommand) GetCbusCommandDecoded() CBusCommand {
	ctx := context.Background()
	_ = ctx
	alpha := m.GetAlpha()
	_ = alpha
	return CastCBusCommand(m.GetCbusCommand())
}

func (m *_RequestCommand) GetChksumDecoded() Checksum {
	ctx := context.Background()
	_ = ctx
	alpha := m.GetAlpha()
	_ = alpha
	return CastChecksum(m.GetChksum())
}

///////////////////////
///////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/////////////////////// Accessors for const fields.
///////////////////////

func (m *_RequestCommand) GetInitiator() byte {
	return RequestCommand_INITIATOR
}

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

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

func (m *_RequestCommand) GetTypeName() string {
	return "RequestCommand"
}

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

	// Const Field (initiator)
	lengthInBits += 8

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

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

	// Manual Field (chksum)
	lengthInBits += uint16(utils.InlineIf((m.GetCBusOptions().GetSrchk()), func() any { return int32((int32(16))) }, func() any { return int32((int32(0))) }).(int32))

	// 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 *_RequestCommand) GetLengthInBytes(ctx context.Context) uint16 {
	return m.GetLengthInBits(ctx) / 8
}

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

	initiator, err := ReadConstField[byte](ctx, "initiator", ReadByte(readBuffer, 8), RequestCommand_INITIATOR)
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'initiator' field"))
	}
	_ = initiator

	cbusCommand, err := ReadManualField[CBusCommand](ctx, "cbusCommand", readBuffer, EnsureType[CBusCommand](ReadCBusCommand(ctx, readBuffer, cBusOptions, cBusOptions.GetSrchk())))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'cbusCommand' field"))
	}
	m.CbusCommand = cbusCommand

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

	chksum, err := ReadManualField[Checksum](ctx, "chksum", readBuffer, EnsureType[Checksum](ReadAndValidateChecksum(ctx, readBuffer, cbusCommand, cBusOptions.GetSrchk())))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'chksum' field"))
	}
	m.Chksum = chksum

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

	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("RequestCommand"); closeErr != nil {
		return nil, errors.Wrap(closeErr, "Error closing for RequestCommand")
	}

	return m, nil
}

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

		if err := WriteConstField(ctx, "initiator", RequestCommand_INITIATOR, WriteByte(writeBuffer, 8)); err != nil {
			return errors.Wrap(err, "Error serializing 'initiator' field")
		}

		if err := WriteManualField[CBusCommand](ctx, "cbusCommand", func(ctx context.Context) error { return WriteCBusCommand(ctx, writeBuffer, m.GetCbusCommand()) }, writeBuffer); err != nil {
			return errors.Wrap(err, "Error serializing 'cbusCommand' field")
		}
		// Virtual field
		cbusCommandDecoded := m.GetCbusCommandDecoded()
		_ = cbusCommandDecoded
		if _cbusCommandDecodedErr := writeBuffer.WriteVirtual(ctx, "cbusCommandDecoded", m.GetCbusCommandDecoded()); _cbusCommandDecodedErr != nil {
			return errors.Wrap(_cbusCommandDecodedErr, "Error serializing 'cbusCommandDecoded' field")
		}

		if err := WriteManualField[Checksum](ctx, "chksum", func(ctx context.Context) error {
			return CalculateChecksum(ctx, writeBuffer, m.GetCbusCommand(), m.GetCBusOptions().GetSrchk())
		}, writeBuffer); err != nil {
			return errors.Wrap(err, "Error serializing 'chksum' field")
		}
		// Virtual field
		chksumDecoded := m.GetChksumDecoded()
		_ = chksumDecoded
		if _chksumDecodedErr := writeBuffer.WriteVirtual(ctx, "chksumDecoded", m.GetChksumDecoded()); _chksumDecodedErr != nil {
			return errors.Wrap(_chksumDecodedErr, "Error serializing 'chksumDecoded' 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("RequestCommand"); popErr != nil {
			return errors.Wrap(popErr, "Error popping for RequestCommand")
		}
		return nil
	}
	return m.RequestContract.(*_Request).serializeParent(ctx, writeBuffer, m, ser)
}

func (m *_RequestCommand) IsRequestCommand() {}

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

func (m *_RequestCommand) deepCopy() *_RequestCommand {
	if m == nil {
		return nil
	}
	_RequestCommandCopy := &_RequestCommand{
		m.RequestContract.(*_Request).deepCopy(),
		utils.DeepCopy[CBusOptions](m.CBusOptions),
		utils.DeepCopy[CBusCommand](m.CbusCommand),
		utils.DeepCopy[Checksum](m.Chksum),
		utils.DeepCopy[Alpha](m.Alpha),
	}
	_RequestCommandCopy.RequestContract.(*_Request)._SubType = m
	return _RequestCommandCopy
}

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