/*
 * 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
 *
 *   http://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 (
	"github.com/apache/plc4x/plc4go/internal/plc4go/spi/utils"
	"github.com/pkg/errors"
	"math"
)

// Code generated by code-generation. DO NOT EDIT.

// The data-structure of this message
type S7VarPayloadDataItem struct {
	ReturnCode    DataTransportErrorCode
	TransportSize DataTransportSize
	Data          []byte
}

// The corresponding interface
type IS7VarPayloadDataItem interface {
	LengthInBytes() uint16
	LengthInBits() uint16
	Serialize(writeBuffer utils.WriteBuffer) error
}

func NewS7VarPayloadDataItem(returnCode DataTransportErrorCode, transportSize DataTransportSize, data []byte) *S7VarPayloadDataItem {
	return &S7VarPayloadDataItem{ReturnCode: returnCode, TransportSize: transportSize, Data: data}
}

func CastS7VarPayloadDataItem(structType interface{}) *S7VarPayloadDataItem {
	castFunc := func(typ interface{}) *S7VarPayloadDataItem {
		if casted, ok := typ.(S7VarPayloadDataItem); ok {
			return &casted
		}
		if casted, ok := typ.(*S7VarPayloadDataItem); ok {
			return casted
		}
		return nil
	}
	return castFunc(structType)
}

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

func (m *S7VarPayloadDataItem) LengthInBits() uint16 {
	return m.LengthInBitsConditional(false)
}

func (m *S7VarPayloadDataItem) LengthInBitsConditional(lastItem bool) 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(lastItem, func() uint16 { return uint16(uint8(0)) }, func() uint16 { return uint16(uint8(uint8(len(m.Data))) % uint8(uint8(2))) }))
	for ; _timesPadding > 0; _timesPadding-- {
		lengthInBits += 8
	}

	return lengthInBits
}

func (m *S7VarPayloadDataItem) LengthInBytes() uint16 {
	return m.LengthInBits() / 8
}

func S7VarPayloadDataItemParse(readBuffer utils.ReadBuffer, lastItem bool) (*S7VarPayloadDataItem, error) {
	if pullErr := readBuffer.PullContext("S7VarPayloadDataItem"); pullErr != nil {
		return nil, pullErr
	}

	// Simple Field (returnCode)
	if pullErr := readBuffer.PullContext("returnCode"); pullErr != nil {
		return nil, pullErr
	}
	returnCode, _returnCodeErr := DataTransportErrorCodeParse(readBuffer)
	if _returnCodeErr != nil {
		return nil, errors.Wrap(_returnCodeErr, "Error parsing 'returnCode' field")
	}
	if closeErr := readBuffer.CloseContext("returnCode"); closeErr != nil {
		return nil, closeErr
	}

	// Simple Field (transportSize)
	if pullErr := readBuffer.PullContext("transportSize"); pullErr != nil {
		return nil, pullErr
	}
	transportSize, _transportSizeErr := DataTransportSizeParse(readBuffer)
	if _transportSizeErr != nil {
		return nil, errors.Wrap(_transportSizeErr, "Error parsing 'transportSize' field")
	}
	if closeErr := readBuffer.CloseContext("transportSize"); closeErr != nil {
		return nil, closeErr
	}

	// Implicit Field (dataLength) (Used for parsing, but it's value is not stored as it's implicitly given by the objects content)
	dataLength, _dataLengthErr := readBuffer.ReadUint16("dataLength", 16)
	_ = dataLength
	if _dataLengthErr != nil {
		return nil, errors.Wrap(_dataLengthErr, "Error parsing 'dataLength' field")
	}
	// Byte Array field (data)
	numberOfBytes := int(utils.InlineIf(transportSize.SizeInBits(), func() uint16 { return uint16(math.Ceil(float64(dataLength) / float64(float64(8.0)))) }, func() uint16 { return uint16(dataLength) }))
	data, _readArrayErr := readBuffer.ReadByteArray("data", numberOfBytes)
	if _readArrayErr != nil {
		return nil, errors.Wrap(_readArrayErr, "Error parsing 'data' field")
	}

	// Padding Field (padding)
	{
		if pullErr := readBuffer.PullContext("padding", utils.WithRenderAsList(true)); pullErr != nil {
			return nil, pullErr
		}
		_timesPadding := (utils.InlineIf(lastItem, func() uint16 { return uint16(uint8(0)) }, func() uint16 { return uint16(uint8(uint8(len(data))) % uint8(uint8(2))) }))
		for ; (readBuffer.HasMore(8)) && (_timesPadding > 0); _timesPadding-- {
			// Just read the padding data and ignore it
			_, _err := readBuffer.ReadUint8("", 8)
			if _err != nil {
				return nil, errors.Wrap(_err, "Error parsing 'padding' field")
			}
		}
		if closeErr := readBuffer.CloseContext("padding", utils.WithRenderAsList(true)); closeErr != nil {
			return nil, closeErr
		}
	}

	if closeErr := readBuffer.CloseContext("S7VarPayloadDataItem"); closeErr != nil {
		return nil, closeErr
	}

	// Create the instance
	return NewS7VarPayloadDataItem(returnCode, transportSize, data), nil
}

func (m *S7VarPayloadDataItem) Serialize(writeBuffer utils.WriteBuffer, lastItem bool) error {
	if pushErr := writeBuffer.PushContext("S7VarPayloadDataItem"); pushErr != nil {
		return pushErr
	}

	// Simple Field (returnCode)
	if pushErr := writeBuffer.PushContext("returnCode"); pushErr != nil {
		return pushErr
	}
	_returnCodeErr := m.ReturnCode.Serialize(writeBuffer)
	if popErr := writeBuffer.PopContext("returnCode"); popErr != nil {
		return popErr
	}
	if _returnCodeErr != nil {
		return errors.Wrap(_returnCodeErr, "Error serializing 'returnCode' field")
	}

	// Simple Field (transportSize)
	if pushErr := writeBuffer.PushContext("transportSize"); pushErr != nil {
		return pushErr
	}
	_transportSizeErr := m.TransportSize.Serialize(writeBuffer)
	if popErr := writeBuffer.PopContext("transportSize"); popErr != nil {
		return popErr
	}
	if _transportSizeErr != nil {
		return errors.Wrap(_transportSizeErr, "Error serializing 'transportSize' field")
	}

	// Implicit Field (dataLength) (Used for parsing, but it's value is not stored as it's implicitly given by the objects content)
	dataLength := uint16(uint16(uint16(len(m.Data))) * uint16(uint16(utils.InlineIf(bool(bool((m.TransportSize) == (DataTransportSize_BIT))), func() uint16 { return uint16(uint16(1)) }, func() uint16 {
		return uint16(uint16(utils.InlineIf(m.TransportSize.SizeInBits(), func() uint16 { return uint16(uint16(8)) }, func() uint16 { return uint16(uint16(1)) })))
	}))))
	_dataLengthErr := writeBuffer.WriteUint16("dataLength", 16, (dataLength))
	if _dataLengthErr != nil {
		return errors.Wrap(_dataLengthErr, "Error serializing 'dataLength' field")
	}

	// Array Field (data)
	if m.Data != nil {
		// Byte Array field (data)
		_writeArrayErr := writeBuffer.WriteByteArray("data", m.Data)
		if _writeArrayErr != nil {
			return errors.Wrap(_writeArrayErr, "Error serializing 'data' field")
		}
	}

	// Padding Field (padding)
	{
		if pushErr := writeBuffer.PushContext("padding", utils.WithRenderAsList(true)); pushErr != nil {
			return pushErr
		}
		_timesPadding := uint8(utils.InlineIf(lastItem, func() uint16 { return uint16(uint8(0)) }, func() uint16 { return uint16(uint8(uint8(len(m.Data))) % uint8(uint8(2))) }))
		for ; _timesPadding > 0; _timesPadding-- {
			_paddingValue := uint8(uint8(0))
			_paddingErr := writeBuffer.WriteUint8("", 8, (_paddingValue))
			if _paddingErr != nil {
				return errors.Wrap(_paddingErr, "Error serializing 'padding' field")
			}
		}
		if popErr := writeBuffer.PopContext("padding", utils.WithRenderAsList(true)); popErr != nil {
			return popErr
		}
	}

	if popErr := writeBuffer.PopContext("S7VarPayloadDataItem"); popErr != nil {
		return popErr
	}
	return nil
}
