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

// S7PayloadReadVarResponse is the corresponding interface of S7PayloadReadVarResponse
type S7PayloadReadVarResponse interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	S7Payload
	// GetItems returns Items (property field)
	GetItems() []S7VarPayloadDataItem
	// IsS7PayloadReadVarResponse is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsS7PayloadReadVarResponse()
	// CreateBuilder creates a S7PayloadReadVarResponseBuilder
	CreateS7PayloadReadVarResponseBuilder() S7PayloadReadVarResponseBuilder
}

// _S7PayloadReadVarResponse is the data-structure of this message
type _S7PayloadReadVarResponse struct {
	S7PayloadContract
	Items []S7VarPayloadDataItem
}

var _ S7PayloadReadVarResponse = (*_S7PayloadReadVarResponse)(nil)
var _ S7PayloadRequirements = (*_S7PayloadReadVarResponse)(nil)

// NewS7PayloadReadVarResponse factory function for _S7PayloadReadVarResponse
func NewS7PayloadReadVarResponse(items []S7VarPayloadDataItem, parameter S7Parameter) *_S7PayloadReadVarResponse {
	_result := &_S7PayloadReadVarResponse{
		S7PayloadContract: NewS7Payload(parameter),
		Items:             items,
	}
	_result.S7PayloadContract.(*_S7Payload)._SubType = _result
	return _result
}

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

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

// NewS7PayloadReadVarResponseBuilder() creates a S7PayloadReadVarResponseBuilder
func NewS7PayloadReadVarResponseBuilder() S7PayloadReadVarResponseBuilder {
	return &_S7PayloadReadVarResponseBuilder{_S7PayloadReadVarResponse: new(_S7PayloadReadVarResponse)}
}

type _S7PayloadReadVarResponseBuilder struct {
	*_S7PayloadReadVarResponse

	parentBuilder *_S7PayloadBuilder

	err *utils.MultiError
}

var _ (S7PayloadReadVarResponseBuilder) = (*_S7PayloadReadVarResponseBuilder)(nil)

func (b *_S7PayloadReadVarResponseBuilder) setParent(contract S7PayloadContract) {
	b.S7PayloadContract = contract
	contract.(*_S7Payload)._SubType = b._S7PayloadReadVarResponse
}

func (b *_S7PayloadReadVarResponseBuilder) WithMandatoryFields(items []S7VarPayloadDataItem) S7PayloadReadVarResponseBuilder {
	return b.WithItems(items...)
}

func (b *_S7PayloadReadVarResponseBuilder) WithItems(items ...S7VarPayloadDataItem) S7PayloadReadVarResponseBuilder {
	b.Items = items
	return b
}

func (b *_S7PayloadReadVarResponseBuilder) Build() (S7PayloadReadVarResponse, error) {
	if b.err != nil {
		return nil, errors.Wrap(b.err, "error occurred during build")
	}
	return b._S7PayloadReadVarResponse.deepCopy(), nil
}

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

func (b *_S7PayloadReadVarResponseBuilder) Done() S7PayloadBuilder {
	if b.parentBuilder == nil {
		b.parentBuilder = NewS7PayloadBuilder().(*_S7PayloadBuilder)
	}
	return b.parentBuilder
}

func (b *_S7PayloadReadVarResponseBuilder) buildForS7Payload() (S7Payload, error) {
	return b.Build()
}

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

// CreateS7PayloadReadVarResponseBuilder creates a S7PayloadReadVarResponseBuilder
func (b *_S7PayloadReadVarResponse) CreateS7PayloadReadVarResponseBuilder() S7PayloadReadVarResponseBuilder {
	if b == nil {
		return NewS7PayloadReadVarResponseBuilder()
	}
	return &_S7PayloadReadVarResponseBuilder{_S7PayloadReadVarResponse: b.deepCopy()}
}

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

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

func (m *_S7PayloadReadVarResponse) GetParameterParameterType() uint8 {
	return 0x04
}

func (m *_S7PayloadReadVarResponse) GetMessageType() uint8 {
	return 0x03
}

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

func (m *_S7PayloadReadVarResponse) GetParent() S7PayloadContract {
	return m.S7PayloadContract
}

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

func (m *_S7PayloadReadVarResponse) GetItems() []S7VarPayloadDataItem {
	return m.Items
}

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

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

func (m *_S7PayloadReadVarResponse) GetTypeName() string {
	return "S7PayloadReadVarResponse"
}

func (m *_S7PayloadReadVarResponse) GetLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(m.S7PayloadContract.(*_S7Payload).getLengthInBits(ctx))

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

	return lengthInBits
}

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

func (m *_S7PayloadReadVarResponse) parse(ctx context.Context, readBuffer utils.ReadBuffer, parent *_S7Payload, messageType uint8, parameter S7Parameter) (__s7PayloadReadVarResponse S7PayloadReadVarResponse, err error) {
	m.S7PayloadContract = parent
	parent._SubType = m
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("S7PayloadReadVarResponse"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for S7PayloadReadVarResponse")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

	items, err := ReadCountArrayField[S7VarPayloadDataItem](ctx, "items", ReadComplex[S7VarPayloadDataItem](S7VarPayloadDataItemParseWithBuffer, readBuffer), uint64(CastS7ParameterReadVarResponse(parameter).GetNumItems()))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'items' field"))
	}
	m.Items = items

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

	return m, nil
}

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

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

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

func (m *_S7PayloadReadVarResponse) IsS7PayloadReadVarResponse() {}

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

func (m *_S7PayloadReadVarResponse) deepCopy() *_S7PayloadReadVarResponse {
	if m == nil {
		return nil
	}
	_S7PayloadReadVarResponseCopy := &_S7PayloadReadVarResponse{
		m.S7PayloadContract.(*_S7Payload).deepCopy(),
		utils.DeepCopySlice[S7VarPayloadDataItem, S7VarPayloadDataItem](m.Items),
	}
	_S7PayloadReadVarResponseCopy.S7PayloadContract.(*_S7Payload)._SubType = m
	return _S7PayloadReadVarResponseCopy
}

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