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

// ModbusPDUReadFileRecordRequest is the corresponding interface of ModbusPDUReadFileRecordRequest
// File Record Access
type ModbusPDUReadFileRecordRequest interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ModbusPDU
	// GetItems returns Items (property field)
	GetItems() []ModbusPDUReadFileRecordRequestItem
	// IsModbusPDUReadFileRecordRequest is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsModbusPDUReadFileRecordRequest()
	// CreateBuilder creates a ModbusPDUReadFileRecordRequestBuilder
	CreateModbusPDUReadFileRecordRequestBuilder() ModbusPDUReadFileRecordRequestBuilder
}

// _ModbusPDUReadFileRecordRequest is the data-structure of this message
type _ModbusPDUReadFileRecordRequest struct {
	ModbusPDUContract
	Items []ModbusPDUReadFileRecordRequestItem
}

var _ ModbusPDUReadFileRecordRequest = (*_ModbusPDUReadFileRecordRequest)(nil)
var _ ModbusPDURequirements = (*_ModbusPDUReadFileRecordRequest)(nil)

// NewModbusPDUReadFileRecordRequest factory function for _ModbusPDUReadFileRecordRequest
func NewModbusPDUReadFileRecordRequest(items []ModbusPDUReadFileRecordRequestItem) *_ModbusPDUReadFileRecordRequest {
	_result := &_ModbusPDUReadFileRecordRequest{
		ModbusPDUContract: NewModbusPDU(),
		Items:             items,
	}
	_result.ModbusPDUContract.(*_ModbusPDU)._SubType = _result
	return _result
}

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

// ModbusPDUReadFileRecordRequestBuilder is a builder for ModbusPDUReadFileRecordRequest
type ModbusPDUReadFileRecordRequestBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(items []ModbusPDUReadFileRecordRequestItem) ModbusPDUReadFileRecordRequestBuilder
	// WithItems adds Items (property field)
	WithItems(...ModbusPDUReadFileRecordRequestItem) ModbusPDUReadFileRecordRequestBuilder
	// Done is used to finish work on this child and return (or create one if none) to the parent builder
	Done() ModbusPDUBuilder
	// Build builds the ModbusPDUReadFileRecordRequest or returns an error if something is wrong
	Build() (ModbusPDUReadFileRecordRequest, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() ModbusPDUReadFileRecordRequest
}

// NewModbusPDUReadFileRecordRequestBuilder() creates a ModbusPDUReadFileRecordRequestBuilder
func NewModbusPDUReadFileRecordRequestBuilder() ModbusPDUReadFileRecordRequestBuilder {
	return &_ModbusPDUReadFileRecordRequestBuilder{_ModbusPDUReadFileRecordRequest: new(_ModbusPDUReadFileRecordRequest)}
}

type _ModbusPDUReadFileRecordRequestBuilder struct {
	*_ModbusPDUReadFileRecordRequest

	parentBuilder *_ModbusPDUBuilder

	collectedErr []error
}

var _ (ModbusPDUReadFileRecordRequestBuilder) = (*_ModbusPDUReadFileRecordRequestBuilder)(nil)

func (b *_ModbusPDUReadFileRecordRequestBuilder) setParent(contract ModbusPDUContract) {
	b.ModbusPDUContract = contract
	contract.(*_ModbusPDU)._SubType = b._ModbusPDUReadFileRecordRequest
}

func (b *_ModbusPDUReadFileRecordRequestBuilder) WithMandatoryFields(items []ModbusPDUReadFileRecordRequestItem) ModbusPDUReadFileRecordRequestBuilder {
	return b.WithItems(items...)
}

func (b *_ModbusPDUReadFileRecordRequestBuilder) WithItems(items ...ModbusPDUReadFileRecordRequestItem) ModbusPDUReadFileRecordRequestBuilder {
	b.Items = items
	return b
}

func (b *_ModbusPDUReadFileRecordRequestBuilder) Build() (ModbusPDUReadFileRecordRequest, error) {
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._ModbusPDUReadFileRecordRequest.deepCopy(), nil
}

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

func (b *_ModbusPDUReadFileRecordRequestBuilder) Done() ModbusPDUBuilder {
	if b.parentBuilder == nil {
		b.parentBuilder = NewModbusPDUBuilder().(*_ModbusPDUBuilder)
	}
	return b.parentBuilder
}

func (b *_ModbusPDUReadFileRecordRequestBuilder) buildForModbusPDU() (ModbusPDU, error) {
	return b.Build()
}

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

// CreateModbusPDUReadFileRecordRequestBuilder creates a ModbusPDUReadFileRecordRequestBuilder
func (b *_ModbusPDUReadFileRecordRequest) CreateModbusPDUReadFileRecordRequestBuilder() ModbusPDUReadFileRecordRequestBuilder {
	if b == nil {
		return NewModbusPDUReadFileRecordRequestBuilder()
	}
	return &_ModbusPDUReadFileRecordRequestBuilder{_ModbusPDUReadFileRecordRequest: b.deepCopy()}
}

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

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

func (m *_ModbusPDUReadFileRecordRequest) GetErrorFlag() bool {
	return bool(false)
}

func (m *_ModbusPDUReadFileRecordRequest) GetFunctionFlag() uint8 {
	return 0x14
}

func (m *_ModbusPDUReadFileRecordRequest) GetResponse() bool {
	return bool(false)
}

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

func (m *_ModbusPDUReadFileRecordRequest) GetParent() ModbusPDUContract {
	return m.ModbusPDUContract
}

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

func (m *_ModbusPDUReadFileRecordRequest) GetItems() []ModbusPDUReadFileRecordRequestItem {
	return m.Items
}

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

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

func (m *_ModbusPDUReadFileRecordRequest) GetTypeName() string {
	return "ModbusPDUReadFileRecordRequest"
}

func (m *_ModbusPDUReadFileRecordRequest) GetLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(m.ModbusPDUContract.(*_ModbusPDU).getLengthInBits(ctx))

	// Implicit Field (byteCount)
	lengthInBits += 8

	// Array field
	if len(m.Items) > 0 {
		for _, element := range m.Items {
			lengthInBits += element.GetLengthInBits(ctx)
		}
	}

	return lengthInBits
}

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

func (m *_ModbusPDUReadFileRecordRequest) parse(ctx context.Context, readBuffer utils.ReadBuffer, parent *_ModbusPDU, response bool) (__modbusPDUReadFileRecordRequest ModbusPDUReadFileRecordRequest, err error) {
	m.ModbusPDUContract = parent
	parent._SubType = m
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("ModbusPDUReadFileRecordRequest"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for ModbusPDUReadFileRecordRequest")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

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

	items, err := ReadLengthArrayField[ModbusPDUReadFileRecordRequestItem](ctx, "items", ReadComplex[ModbusPDUReadFileRecordRequestItem](ModbusPDUReadFileRecordRequestItemParseWithBuffer, readBuffer), int(byteCount))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'items' field"))
	}
	m.Items = items

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

	return m, nil
}

func (m *_ModbusPDUReadFileRecordRequest) 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 *_ModbusPDUReadFileRecordRequest) SerializeWithWriteBuffer(ctx context.Context, writeBuffer utils.WriteBuffer) error {
	positionAware := writeBuffer
	_ = positionAware
	log := zerolog.Ctx(ctx)
	_ = log
	itemsArraySizeInBytes := func(items []ModbusPDUReadFileRecordRequestItem) uint32 {
		var sizeInBytes uint32 = 0
		for _, v := range items {
			sizeInBytes += uint32(v.GetLengthInBytes(ctx))
		}
		return sizeInBytes
	}
	ser := func() error {
		if pushErr := writeBuffer.PushContext("ModbusPDUReadFileRecordRequest"); pushErr != nil {
			return errors.Wrap(pushErr, "Error pushing for ModbusPDUReadFileRecordRequest")
		}
		byteCount := uint8(uint8(itemsArraySizeInBytes(m.GetItems())))
		if err := WriteImplicitField(ctx, "byteCount", byteCount, WriteUnsignedByte(writeBuffer, 8)); err != nil {
			return errors.Wrap(err, "Error serializing 'byteCount' field")
		}

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

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

func (m *_ModbusPDUReadFileRecordRequest) IsModbusPDUReadFileRecordRequest() {}

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

func (m *_ModbusPDUReadFileRecordRequest) deepCopy() *_ModbusPDUReadFileRecordRequest {
	if m == nil {
		return nil
	}
	_ModbusPDUReadFileRecordRequestCopy := &_ModbusPDUReadFileRecordRequest{
		m.ModbusPDUContract.(*_ModbusPDU).deepCopy(),
		utils.DeepCopySlice[ModbusPDUReadFileRecordRequestItem, ModbusPDUReadFileRecordRequestItem](m.Items),
	}
	_ModbusPDUReadFileRecordRequestCopy.ModbusPDUContract.(*_ModbusPDU)._SubType = m
	return _ModbusPDUReadFileRecordRequestCopy
}

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