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

// CBusMessageToClient is the corresponding interface of CBusMessageToClient
type CBusMessageToClient interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	CBusMessage
	// GetReply returns Reply (property field)
	GetReply() ReplyOrConfirmation
	// IsCBusMessageToClient is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsCBusMessageToClient()
	// CreateBuilder creates a CBusMessageToClientBuilder
	CreateCBusMessageToClientBuilder() CBusMessageToClientBuilder
}

// _CBusMessageToClient is the data-structure of this message
type _CBusMessageToClient struct {
	CBusMessageContract
	Reply ReplyOrConfirmation
}

var _ CBusMessageToClient = (*_CBusMessageToClient)(nil)
var _ CBusMessageRequirements = (*_CBusMessageToClient)(nil)

// NewCBusMessageToClient factory function for _CBusMessageToClient
func NewCBusMessageToClient(reply ReplyOrConfirmation) *_CBusMessageToClient {
	if reply == nil {
		panic("reply of type ReplyOrConfirmation for CBusMessageToClient must not be nil")
	}
	_result := &_CBusMessageToClient{
		CBusMessageContract: NewCBusMessage(),
		Reply:               reply,
	}
	_result.CBusMessageContract.(*_CBusMessage)._SubType = _result
	return _result
}

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

// CBusMessageToClientBuilder is a builder for CBusMessageToClient
type CBusMessageToClientBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(reply ReplyOrConfirmation) CBusMessageToClientBuilder
	// WithReply adds Reply (property field)
	WithReply(ReplyOrConfirmation) CBusMessageToClientBuilder
	// WithReplyBuilder adds Reply (property field) which is build by the builder
	WithReplyBuilder(func(ReplyOrConfirmationBuilder) ReplyOrConfirmationBuilder) CBusMessageToClientBuilder
	// Done is used to finish work on this child and return (or create one if none) to the parent builder
	Done() CBusMessageBuilder
	// Build builds the CBusMessageToClient or returns an error if something is wrong
	Build() (CBusMessageToClient, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() CBusMessageToClient
}

// NewCBusMessageToClientBuilder() creates a CBusMessageToClientBuilder
func NewCBusMessageToClientBuilder() CBusMessageToClientBuilder {
	return &_CBusMessageToClientBuilder{_CBusMessageToClient: new(_CBusMessageToClient)}
}

type _CBusMessageToClientBuilder struct {
	*_CBusMessageToClient

	parentBuilder *_CBusMessageBuilder

	collectedErr []error
}

var _ (CBusMessageToClientBuilder) = (*_CBusMessageToClientBuilder)(nil)

func (b *_CBusMessageToClientBuilder) setParent(contract CBusMessageContract) {
	b.CBusMessageContract = contract
	contract.(*_CBusMessage)._SubType = b._CBusMessageToClient
}

func (b *_CBusMessageToClientBuilder) WithMandatoryFields(reply ReplyOrConfirmation) CBusMessageToClientBuilder {
	return b.WithReply(reply)
}

func (b *_CBusMessageToClientBuilder) WithReply(reply ReplyOrConfirmation) CBusMessageToClientBuilder {
	b.Reply = reply
	return b
}

func (b *_CBusMessageToClientBuilder) WithReplyBuilder(builderSupplier func(ReplyOrConfirmationBuilder) ReplyOrConfirmationBuilder) CBusMessageToClientBuilder {
	builder := builderSupplier(b.Reply.CreateReplyOrConfirmationBuilder())
	var err error
	b.Reply, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "ReplyOrConfirmationBuilder failed"))
	}
	return b
}

func (b *_CBusMessageToClientBuilder) Build() (CBusMessageToClient, error) {
	if b.Reply == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'reply' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._CBusMessageToClient.deepCopy(), nil
}

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

func (b *_CBusMessageToClientBuilder) Done() CBusMessageBuilder {
	if b.parentBuilder == nil {
		b.parentBuilder = NewCBusMessageBuilder().(*_CBusMessageBuilder)
	}
	return b.parentBuilder
}

func (b *_CBusMessageToClientBuilder) buildForCBusMessage() (CBusMessage, error) {
	return b.Build()
}

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

// CreateCBusMessageToClientBuilder creates a CBusMessageToClientBuilder
func (b *_CBusMessageToClient) CreateCBusMessageToClientBuilder() CBusMessageToClientBuilder {
	if b == nil {
		return NewCBusMessageToClientBuilder()
	}
	return &_CBusMessageToClientBuilder{_CBusMessageToClient: b.deepCopy()}
}

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

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

func (m *_CBusMessageToClient) GetIsResponse() bool {
	return bool(true)
}

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

func (m *_CBusMessageToClient) GetParent() CBusMessageContract {
	return m.CBusMessageContract
}

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

func (m *_CBusMessageToClient) GetReply() ReplyOrConfirmation {
	return m.Reply
}

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

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

func (m *_CBusMessageToClient) GetTypeName() string {
	return "CBusMessageToClient"
}

func (m *_CBusMessageToClient) GetLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(m.CBusMessageContract.(*_CBusMessage).getLengthInBits(ctx))

	// Simple field (reply)
	lengthInBits += m.Reply.GetLengthInBits(ctx)

	return lengthInBits
}

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

func (m *_CBusMessageToClient) parse(ctx context.Context, readBuffer utils.ReadBuffer, parent *_CBusMessage, isResponse bool, requestContext RequestContext, cBusOptions CBusOptions) (__cBusMessageToClient CBusMessageToClient, err error) {
	m.CBusMessageContract = parent
	parent._SubType = m
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("CBusMessageToClient"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for CBusMessageToClient")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

	reply, err := ReadSimpleField[ReplyOrConfirmation](ctx, "reply", ReadComplex[ReplyOrConfirmation](ReplyOrConfirmationParseWithBufferProducer[ReplyOrConfirmation]((CBusOptions)(cBusOptions), (RequestContext)(requestContext)), readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'reply' field"))
	}
	m.Reply = reply

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

	return m, nil
}

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

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

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

func (m *_CBusMessageToClient) IsCBusMessageToClient() {}

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

func (m *_CBusMessageToClient) deepCopy() *_CBusMessageToClient {
	if m == nil {
		return nil
	}
	_CBusMessageToClientCopy := &_CBusMessageToClient{
		m.CBusMessageContract.(*_CBusMessage).deepCopy(),
		utils.DeepCopy[ReplyOrConfirmation](m.Reply),
	}
	_CBusMessageToClientCopy.CBusMessageContract.(*_CBusMessage)._SubType = m
	return _CBusMessageToClientCopy
}

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