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

// ReadRequest is the corresponding interface of ReadRequest
type ReadRequest interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetRequestHeader returns RequestHeader (property field)
	GetRequestHeader() RequestHeader
	// GetMaxAge returns MaxAge (property field)
	GetMaxAge() float64
	// GetTimestampsToReturn returns TimestampsToReturn (property field)
	GetTimestampsToReturn() TimestampsToReturn
	// GetNodesToRead returns NodesToRead (property field)
	GetNodesToRead() []ReadValueId
	// IsReadRequest is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsReadRequest()
	// CreateBuilder creates a ReadRequestBuilder
	CreateReadRequestBuilder() ReadRequestBuilder
}

// _ReadRequest is the data-structure of this message
type _ReadRequest struct {
	ExtensionObjectDefinitionContract
	RequestHeader      RequestHeader
	MaxAge             float64
	TimestampsToReturn TimestampsToReturn
	NodesToRead        []ReadValueId
}

var _ ReadRequest = (*_ReadRequest)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_ReadRequest)(nil)

// NewReadRequest factory function for _ReadRequest
func NewReadRequest(requestHeader RequestHeader, maxAge float64, timestampsToReturn TimestampsToReturn, nodesToRead []ReadValueId) *_ReadRequest {
	if requestHeader == nil {
		panic("requestHeader of type RequestHeader for ReadRequest must not be nil")
	}
	_result := &_ReadRequest{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		RequestHeader:                     requestHeader,
		MaxAge:                            maxAge,
		TimestampsToReturn:                timestampsToReturn,
		NodesToRead:                       nodesToRead,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// ReadRequestBuilder is a builder for ReadRequest
type ReadRequestBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(requestHeader RequestHeader, maxAge float64, timestampsToReturn TimestampsToReturn, nodesToRead []ReadValueId) ReadRequestBuilder
	// WithRequestHeader adds RequestHeader (property field)
	WithRequestHeader(RequestHeader) ReadRequestBuilder
	// WithRequestHeaderBuilder adds RequestHeader (property field) which is build by the builder
	WithRequestHeaderBuilder(func(RequestHeaderBuilder) RequestHeaderBuilder) ReadRequestBuilder
	// WithMaxAge adds MaxAge (property field)
	WithMaxAge(float64) ReadRequestBuilder
	// WithTimestampsToReturn adds TimestampsToReturn (property field)
	WithTimestampsToReturn(TimestampsToReturn) ReadRequestBuilder
	// WithNodesToRead adds NodesToRead (property field)
	WithNodesToRead(...ReadValueId) ReadRequestBuilder
	// Done is used to finish work on this child and return (or create one if none) to the parent builder
	Done() ExtensionObjectDefinitionBuilder
	// Build builds the ReadRequest or returns an error if something is wrong
	Build() (ReadRequest, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() ReadRequest
}

// NewReadRequestBuilder() creates a ReadRequestBuilder
func NewReadRequestBuilder() ReadRequestBuilder {
	return &_ReadRequestBuilder{_ReadRequest: new(_ReadRequest)}
}

type _ReadRequestBuilder struct {
	*_ReadRequest

	parentBuilder *_ExtensionObjectDefinitionBuilder

	err *utils.MultiError
}

var _ (ReadRequestBuilder) = (*_ReadRequestBuilder)(nil)

func (b *_ReadRequestBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._ReadRequest
}

func (b *_ReadRequestBuilder) WithMandatoryFields(requestHeader RequestHeader, maxAge float64, timestampsToReturn TimestampsToReturn, nodesToRead []ReadValueId) ReadRequestBuilder {
	return b.WithRequestHeader(requestHeader).WithMaxAge(maxAge).WithTimestampsToReturn(timestampsToReturn).WithNodesToRead(nodesToRead...)
}

func (b *_ReadRequestBuilder) WithRequestHeader(requestHeader RequestHeader) ReadRequestBuilder {
	b.RequestHeader = requestHeader
	return b
}

func (b *_ReadRequestBuilder) WithRequestHeaderBuilder(builderSupplier func(RequestHeaderBuilder) RequestHeaderBuilder) ReadRequestBuilder {
	builder := builderSupplier(b.RequestHeader.CreateRequestHeaderBuilder())
	var err error
	b.RequestHeader, err = builder.Build()
	if err != nil {
		if b.err == nil {
			b.err = &utils.MultiError{MainError: errors.New("sub builder failed")}
		}
		b.err.Append(errors.Wrap(err, "RequestHeaderBuilder failed"))
	}
	return b
}

func (b *_ReadRequestBuilder) WithMaxAge(maxAge float64) ReadRequestBuilder {
	b.MaxAge = maxAge
	return b
}

func (b *_ReadRequestBuilder) WithTimestampsToReturn(timestampsToReturn TimestampsToReturn) ReadRequestBuilder {
	b.TimestampsToReturn = timestampsToReturn
	return b
}

func (b *_ReadRequestBuilder) WithNodesToRead(nodesToRead ...ReadValueId) ReadRequestBuilder {
	b.NodesToRead = nodesToRead
	return b
}

func (b *_ReadRequestBuilder) Build() (ReadRequest, error) {
	if b.RequestHeader == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'requestHeader' not set"))
	}
	if b.err != nil {
		return nil, errors.Wrap(b.err, "error occurred during build")
	}
	return b._ReadRequest.deepCopy(), nil
}

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

func (b *_ReadRequestBuilder) Done() ExtensionObjectDefinitionBuilder {
	if b.parentBuilder == nil {
		b.parentBuilder = NewExtensionObjectDefinitionBuilder().(*_ExtensionObjectDefinitionBuilder)
	}
	return b.parentBuilder
}

func (b *_ReadRequestBuilder) buildForExtensionObjectDefinition() (ExtensionObjectDefinition, error) {
	return b.Build()
}

func (b *_ReadRequestBuilder) DeepCopy() any {
	_copy := b.CreateReadRequestBuilder().(*_ReadRequestBuilder)
	if b.err != nil {
		_copy.err = b.err.DeepCopy().(*utils.MultiError)
	}
	return _copy
}

// CreateReadRequestBuilder creates a ReadRequestBuilder
func (b *_ReadRequest) CreateReadRequestBuilder() ReadRequestBuilder {
	if b == nil {
		return NewReadRequestBuilder()
	}
	return &_ReadRequestBuilder{_ReadRequest: b.deepCopy()}
}

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

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

func (m *_ReadRequest) GetExtensionId() int32 {
	return int32(631)
}

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

func (m *_ReadRequest) GetParent() ExtensionObjectDefinitionContract {
	return m.ExtensionObjectDefinitionContract
}

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

func (m *_ReadRequest) GetRequestHeader() RequestHeader {
	return m.RequestHeader
}

func (m *_ReadRequest) GetMaxAge() float64 {
	return m.MaxAge
}

func (m *_ReadRequest) GetTimestampsToReturn() TimestampsToReturn {
	return m.TimestampsToReturn
}

func (m *_ReadRequest) GetNodesToRead() []ReadValueId {
	return m.NodesToRead
}

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

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

func (m *_ReadRequest) GetTypeName() string {
	return "ReadRequest"
}

func (m *_ReadRequest) GetLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).getLengthInBits(ctx))

	// Simple field (requestHeader)
	lengthInBits += m.RequestHeader.GetLengthInBits(ctx)

	// Simple field (maxAge)
	lengthInBits += 64

	// Simple field (timestampsToReturn)
	lengthInBits += 32

	// Implicit Field (noOfNodesToRead)
	lengthInBits += 32

	// Array field
	if len(m.NodesToRead) > 0 {
		for _curItem, element := range m.NodesToRead {
			arrayCtx := utils.CreateArrayContext(ctx, len(m.NodesToRead), _curItem)
			lengthInBits += element.GetLengthInBits(arrayCtx)
		}
	}

	return lengthInBits
}

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

func (m *_ReadRequest) parse(ctx context.Context, readBuffer utils.ReadBuffer, parent *_ExtensionObjectDefinition, extensionId int32) (__readRequest ReadRequest, err error) {
	m.ExtensionObjectDefinitionContract = parent
	parent._SubType = m
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("ReadRequest"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for ReadRequest")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

	requestHeader, err := ReadSimpleField[RequestHeader](ctx, "requestHeader", ReadComplex[RequestHeader](ExtensionObjectDefinitionParseWithBufferProducer[RequestHeader]((int32)(int32(391))), readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'requestHeader' field"))
	}
	m.RequestHeader = requestHeader

	maxAge, err := ReadSimpleField(ctx, "maxAge", ReadDouble(readBuffer, uint8(64)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'maxAge' field"))
	}
	m.MaxAge = maxAge

	timestampsToReturn, err := ReadEnumField[TimestampsToReturn](ctx, "timestampsToReturn", "TimestampsToReturn", ReadEnum(TimestampsToReturnByValue, ReadUnsignedInt(readBuffer, uint8(32))))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'timestampsToReturn' field"))
	}
	m.TimestampsToReturn = timestampsToReturn

	noOfNodesToRead, err := ReadImplicitField[int32](ctx, "noOfNodesToRead", ReadSignedInt(readBuffer, uint8(32)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'noOfNodesToRead' field"))
	}
	_ = noOfNodesToRead

	nodesToRead, err := ReadCountArrayField[ReadValueId](ctx, "nodesToRead", ReadComplex[ReadValueId](ExtensionObjectDefinitionParseWithBufferProducer[ReadValueId]((int32)(int32(628))), readBuffer), uint64(noOfNodesToRead))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'nodesToRead' field"))
	}
	m.NodesToRead = nodesToRead

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

	return m, nil
}

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

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

		if err := WriteSimpleField[float64](ctx, "maxAge", m.GetMaxAge(), WriteDouble(writeBuffer, 64)); err != nil {
			return errors.Wrap(err, "Error serializing 'maxAge' field")
		}

		if err := WriteSimpleEnumField[TimestampsToReturn](ctx, "timestampsToReturn", "TimestampsToReturn", m.GetTimestampsToReturn(), WriteEnum[TimestampsToReturn, uint32](TimestampsToReturn.GetValue, TimestampsToReturn.PLC4XEnumName, WriteUnsignedInt(writeBuffer, 32))); err != nil {
			return errors.Wrap(err, "Error serializing 'timestampsToReturn' field")
		}
		noOfNodesToRead := int32(utils.InlineIf(bool((m.GetNodesToRead()) == (nil)), func() any { return int32(-(int32(1))) }, func() any { return int32(int32(len(m.GetNodesToRead()))) }).(int32))
		if err := WriteImplicitField(ctx, "noOfNodesToRead", noOfNodesToRead, WriteSignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'noOfNodesToRead' field")
		}

		if err := WriteComplexTypeArrayField(ctx, "nodesToRead", m.GetNodesToRead(), writeBuffer); err != nil {
			return errors.Wrap(err, "Error serializing 'nodesToRead' field")
		}

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

func (m *_ReadRequest) IsReadRequest() {}

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

func (m *_ReadRequest) deepCopy() *_ReadRequest {
	if m == nil {
		return nil
	}
	_ReadRequestCopy := &_ReadRequest{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[RequestHeader](m.RequestHeader),
		m.MaxAge,
		m.TimestampsToReturn,
		utils.DeepCopySlice[ReadValueId, ReadValueId](m.NodesToRead),
	}
	_ReadRequestCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _ReadRequestCopy
}

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