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

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

// S7VarPayloadDataItem is the corresponding interface of S7VarPayloadDataItem
// This is actually not quite correct as depending pon the transportSize the length is either defined in bits or bytes.
// @param hasNext In the serialization process, if you have multiple write
//
//	requests the last element does not require padding.
type S7VarPayloadDataItem interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	// GetReturnCode returns ReturnCode (property field)
	GetReturnCode() DataTransportErrorCode
	// GetTransportSize returns TransportSize (property field)
	GetTransportSize() DataTransportSize
	// GetData returns Data (property field)
	GetData() []byte
	// IsS7VarPayloadDataItem is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsS7VarPayloadDataItem()
	// CreateBuilder creates a S7VarPayloadDataItemBuilder
	CreateS7VarPayloadDataItemBuilder() S7VarPayloadDataItemBuilder
}

// _S7VarPayloadDataItem is the data-structure of this message
type _S7VarPayloadDataItem struct {
	ReturnCode    DataTransportErrorCode
	TransportSize DataTransportSize
	Data          []byte
}

var _ S7VarPayloadDataItem = (*_S7VarPayloadDataItem)(nil)

// NewS7VarPayloadDataItem factory function for _S7VarPayloadDataItem
func NewS7VarPayloadDataItem(returnCode DataTransportErrorCode, transportSize DataTransportSize, data []byte) *_S7VarPayloadDataItem {
	return &_S7VarPayloadDataItem{ReturnCode: returnCode, TransportSize: transportSize, Data: data}
}

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

// S7VarPayloadDataItemBuilder is a builder for S7VarPayloadDataItem
type S7VarPayloadDataItemBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(returnCode DataTransportErrorCode, transportSize DataTransportSize, data []byte) S7VarPayloadDataItemBuilder
	// WithReturnCode adds ReturnCode (property field)
	WithReturnCode(DataTransportErrorCode) S7VarPayloadDataItemBuilder
	// WithTransportSize adds TransportSize (property field)
	WithTransportSize(DataTransportSize) S7VarPayloadDataItemBuilder
	// WithData adds Data (property field)
	WithData(...byte) S7VarPayloadDataItemBuilder
	// Build builds the S7VarPayloadDataItem or returns an error if something is wrong
	Build() (S7VarPayloadDataItem, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() S7VarPayloadDataItem
}

// NewS7VarPayloadDataItemBuilder() creates a S7VarPayloadDataItemBuilder
func NewS7VarPayloadDataItemBuilder() S7VarPayloadDataItemBuilder {
	return &_S7VarPayloadDataItemBuilder{_S7VarPayloadDataItem: new(_S7VarPayloadDataItem)}
}

type _S7VarPayloadDataItemBuilder struct {
	*_S7VarPayloadDataItem

	collectedErr []error
}

var _ (S7VarPayloadDataItemBuilder) = (*_S7VarPayloadDataItemBuilder)(nil)

func (b *_S7VarPayloadDataItemBuilder) WithMandatoryFields(returnCode DataTransportErrorCode, transportSize DataTransportSize, data []byte) S7VarPayloadDataItemBuilder {
	return b.WithReturnCode(returnCode).WithTransportSize(transportSize).WithData(data...)
}

func (b *_S7VarPayloadDataItemBuilder) WithReturnCode(returnCode DataTransportErrorCode) S7VarPayloadDataItemBuilder {
	b.ReturnCode = returnCode
	return b
}

func (b *_S7VarPayloadDataItemBuilder) WithTransportSize(transportSize DataTransportSize) S7VarPayloadDataItemBuilder {
	b.TransportSize = transportSize
	return b
}

func (b *_S7VarPayloadDataItemBuilder) WithData(data ...byte) S7VarPayloadDataItemBuilder {
	b.Data = data
	return b
}

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

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

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

// CreateS7VarPayloadDataItemBuilder creates a S7VarPayloadDataItemBuilder
func (b *_S7VarPayloadDataItem) CreateS7VarPayloadDataItemBuilder() S7VarPayloadDataItemBuilder {
	if b == nil {
		return NewS7VarPayloadDataItemBuilder()
	}
	return &_S7VarPayloadDataItemBuilder{_S7VarPayloadDataItem: b.deepCopy()}
}

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

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

func (m *_S7VarPayloadDataItem) GetReturnCode() DataTransportErrorCode {
	return m.ReturnCode
}

func (m *_S7VarPayloadDataItem) GetTransportSize() DataTransportSize {
	return m.TransportSize
}

func (m *_S7VarPayloadDataItem) GetData() []byte {
	return m.Data
}

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

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

func (m *_S7VarPayloadDataItem) GetTypeName() string {
	return "S7VarPayloadDataItem"
}

func (m *_S7VarPayloadDataItem) GetLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(0)

	// Simple field (returnCode)
	lengthInBits += 8

	// Simple field (transportSize)
	lengthInBits += 8

	// Implicit Field (dataLength)
	lengthInBits += 16

	// Array field
	if len(m.Data) > 0 {
		lengthInBits += 8 * uint16(len(m.Data))
	}

	// Padding Field (padding)
	_timesPadding := uint8(utils.InlineIf((!(utils.GetLastItemFromContext(ctx))), func() any { return int32((int32(int32(len(m.GetData()))) % int32(int32(2)))) }, func() any { return int32(int32(0)) }).(int32))
	for ; _timesPadding > 0; _timesPadding-- {
		lengthInBits += 8
	}

	return lengthInBits
}

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

func S7VarPayloadDataItemParse(ctx context.Context, theBytes []byte) (S7VarPayloadDataItem, error) {
	return S7VarPayloadDataItemParseWithBuffer(ctx, utils.NewReadBufferByteBased(theBytes))
}

func S7VarPayloadDataItemParseWithBufferProducer() func(ctx context.Context, readBuffer utils.ReadBuffer) (S7VarPayloadDataItem, error) {
	return func(ctx context.Context, readBuffer utils.ReadBuffer) (S7VarPayloadDataItem, error) {
		return S7VarPayloadDataItemParseWithBuffer(ctx, readBuffer)
	}
}

func S7VarPayloadDataItemParseWithBuffer(ctx context.Context, readBuffer utils.ReadBuffer) (S7VarPayloadDataItem, error) {
	v, err := (new(_S7VarPayloadDataItem)).parse(ctx, readBuffer)
	if err != nil {
		return nil, err
	}
	return v, nil
}

func (m *_S7VarPayloadDataItem) parse(ctx context.Context, readBuffer utils.ReadBuffer) (__s7VarPayloadDataItem S7VarPayloadDataItem, err error) {
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("S7VarPayloadDataItem"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for S7VarPayloadDataItem")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

	returnCode, err := ReadEnumField[DataTransportErrorCode](ctx, "returnCode", "DataTransportErrorCode", ReadEnum(DataTransportErrorCodeByValue, ReadUnsignedByte(readBuffer, uint8(8))))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'returnCode' field"))
	}
	m.ReturnCode = returnCode

	transportSize, err := ReadEnumField[DataTransportSize](ctx, "transportSize", "DataTransportSize", ReadEnum(DataTransportSizeByValue, ReadUnsignedByte(readBuffer, uint8(8))))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'transportSize' field"))
	}
	m.TransportSize = transportSize

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

	data, err := readBuffer.ReadByteArray("data", int(utils.InlineIf(transportSize.SizeInBits(), func() any { return int32(math.Ceil(float64(dataLength) / float64(float64(8.0)))) }, func() any { return int32(dataLength) }).(int32)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'data' field"))
	}
	m.Data = data

	if err := ReadPaddingField(ctx, ReadUnsignedByte(readBuffer, uint8(8)), (int)(utils.InlineIf((!(utils.GetLastItemFromContext(ctx))), func() any { return uint8((uint8(uint8(len(data))) % uint8(uint8(2)))) }, func() any { return uint8(uint8(0)) }).(uint8))); err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing padding field"))
	}

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

	return m, nil
}

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

	if err := WriteSimpleEnumField[DataTransportErrorCode](ctx, "returnCode", "DataTransportErrorCode", m.GetReturnCode(), WriteEnum[DataTransportErrorCode, uint8](DataTransportErrorCode.GetValue, DataTransportErrorCode.PLC4XEnumName, WriteUnsignedByte(writeBuffer, 8))); err != nil {
		return errors.Wrap(err, "Error serializing 'returnCode' field")
	}

	if err := WriteSimpleEnumField[DataTransportSize](ctx, "transportSize", "DataTransportSize", m.GetTransportSize(), WriteEnum[DataTransportSize, uint8](DataTransportSize.GetValue, DataTransportSize.PLC4XEnumName, WriteUnsignedByte(writeBuffer, 8))); err != nil {
		return errors.Wrap(err, "Error serializing 'transportSize' field")
	}
	dataLength := uint16(uint16(uint16(len(m.GetData()))) * uint16((utils.InlineIf((bool((m.GetTransportSize()) == (DataTransportSize_BIT))), func() any { return uint16(uint16(1)) }, func() any {
		return uint16((utils.InlineIf(m.GetTransportSize().SizeInBits(), func() any { return uint16(uint16(8)) }, func() any { return uint16(uint16(1)) }).(uint16)))
	}).(uint16))))
	if err := WriteImplicitField(ctx, "dataLength", dataLength, WriteUnsignedShort(writeBuffer, 16)); err != nil {
		return errors.Wrap(err, "Error serializing 'dataLength' field")
	}

	if err := WriteByteArrayField(ctx, "data", m.GetData(), WriteByteArray(writeBuffer, 8)); err != nil {
		return errors.Wrap(err, "Error serializing 'data' field")
	}

	if err := WritePaddingField[uint8](ctx, "padding", int(utils.InlineIf((!(utils.GetLastItemFromContext(ctx))), func() any { return int32((int32(int32(len(m.GetData()))) % int32(int32(2)))) }, func() any { return int32(int32(0)) }).(int32)), uint8(0x00), WriteUnsignedByte(writeBuffer, 8)); err != nil {
		return errors.Wrap(err, "Error serializing 'padding' field")
	}

	if popErr := writeBuffer.PopContext("S7VarPayloadDataItem"); popErr != nil {
		return errors.Wrap(popErr, "Error popping for S7VarPayloadDataItem")
	}
	return nil
}

func (m *_S7VarPayloadDataItem) IsS7VarPayloadDataItem() {}

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

func (m *_S7VarPayloadDataItem) deepCopy() *_S7VarPayloadDataItem {
	if m == nil {
		return nil
	}
	_S7VarPayloadDataItemCopy := &_S7VarPayloadDataItem{
		m.ReturnCode,
		m.TransportSize,
		utils.DeepCopySlice[byte, byte](m.Data),
	}
	return _S7VarPayloadDataItemCopy
}

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