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

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

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

var _ S7PayloadWriteVarRequest = (*_S7PayloadWriteVarRequest)(nil)
var _ S7PayloadRequirements = (*_S7PayloadWriteVarRequest)(nil)

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

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

// S7PayloadWriteVarRequestBuilder is a builder for S7PayloadWriteVarRequest
type S7PayloadWriteVarRequestBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(items []S7VarPayloadDataItem) S7PayloadWriteVarRequestBuilder
	// WithItems adds Items (property field)
	WithItems(...S7VarPayloadDataItem) S7PayloadWriteVarRequestBuilder
	// 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 S7PayloadWriteVarRequest or returns an error if something is wrong
	Build() (S7PayloadWriteVarRequest, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() S7PayloadWriteVarRequest
}

// NewS7PayloadWriteVarRequestBuilder() creates a S7PayloadWriteVarRequestBuilder
func NewS7PayloadWriteVarRequestBuilder() S7PayloadWriteVarRequestBuilder {
	return &_S7PayloadWriteVarRequestBuilder{_S7PayloadWriteVarRequest: new(_S7PayloadWriteVarRequest)}
}

type _S7PayloadWriteVarRequestBuilder struct {
	*_S7PayloadWriteVarRequest

	parentBuilder *_S7PayloadBuilder

	collectedErr []error
}

var _ (S7PayloadWriteVarRequestBuilder) = (*_S7PayloadWriteVarRequestBuilder)(nil)

func (b *_S7PayloadWriteVarRequestBuilder) setParent(contract S7PayloadContract) {
	b.S7PayloadContract = contract
	contract.(*_S7Payload)._SubType = b._S7PayloadWriteVarRequest
}

func (b *_S7PayloadWriteVarRequestBuilder) WithMandatoryFields(items []S7VarPayloadDataItem) S7PayloadWriteVarRequestBuilder {
	return b.WithItems(items...)
}

func (b *_S7PayloadWriteVarRequestBuilder) WithItems(items ...S7VarPayloadDataItem) S7PayloadWriteVarRequestBuilder {
	b.Items = items
	return b
}

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

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

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

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

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

// CreateS7PayloadWriteVarRequestBuilder creates a S7PayloadWriteVarRequestBuilder
func (b *_S7PayloadWriteVarRequest) CreateS7PayloadWriteVarRequestBuilder() S7PayloadWriteVarRequestBuilder {
	if b == nil {
		return NewS7PayloadWriteVarRequestBuilder()
	}
	return &_S7PayloadWriteVarRequestBuilder{_S7PayloadWriteVarRequest: b.deepCopy()}
}

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

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

func (m *_S7PayloadWriteVarRequest) GetParameterParameterType() uint8 {
	return 0x05
}

func (m *_S7PayloadWriteVarRequest) GetMessageType() uint8 {
	return 0x01
}

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

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

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

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

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

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

func (m *_S7PayloadWriteVarRequest) GetTypeName() string {
	return "S7PayloadWriteVarRequest"
}

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

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

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

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

	return m, nil
}

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

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

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

func (m *_S7PayloadWriteVarRequest) IsS7PayloadWriteVarRequest() {}

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

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

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