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

// AmsSerialFrame is the corresponding interface of AmsSerialFrame
// An AMS packet can be transferred via RS232 with the help of an AMS serial frame.
// The actual AMS packet is in the user data field of the frame.
// The max. length of the AMS packet is limited to 255 bytes.
// Therefore the max. size of an AMS serial frame is 263 bytes.
// The fragment number is compared with an internal counter by the receiver.
// The frame number is simply accepted and not checked when receiving the first AMS frame or in case a timeout is
// exceeded. The CRC16 algorithm is used for calculating the checksum.
// @see <a href="https://infosys.beckhoff.com/content/1033/tcadsamsserialspec/html/tcamssericalspec_amsframe.htm?id=8115637053270715044">TwinCAT AMS via RS232 Specification</a>
type AmsSerialFrame interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	// GetMagicCookie returns MagicCookie (property field)
	// Id for detecting an AMS serial frame.
	GetMagicCookie() uint16
	// GetTransmitterAddress returns TransmitterAddress (property field)
	// Address of the sending participant. This value can always be set to 0 for an RS232 communication,
	// since it is a 1 to 1 connection and hence the participants are unique.
	GetTransmitterAddress() int8
	// GetReceiverAddress returns ReceiverAddress (property field)
	// Receiver’s address. This value can always be set to 0 for an RS232 communication, since it is a 1 to 1
	// connection and hence the participants are unique.
	GetReceiverAddress() int8
	// GetFragmentNumber returns FragmentNumber (property field)
	// Number of the frame sent. Once the number 255 has been sent, it starts again from 0. The receiver checks this
	// number with an internal counter.
	GetFragmentNumber() int8
	// GetLength returns Length (property field)
	// The max. length of the AMS packet to be sent is 255. If larger AMS packets are to be sent then they have to be
	// fragmented (not published at the moment).
	GetLength() int8
	// GetUserdata returns Userdata (property field)
	// The AMS packet to be sent.
	GetUserdata() AmsPacket
	// GetCrc returns Crc (property field)
	GetCrc() uint16
	// IsAmsSerialFrame is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsAmsSerialFrame()
	// CreateBuilder creates a AmsSerialFrameBuilder
	CreateAmsSerialFrameBuilder() AmsSerialFrameBuilder
}

// _AmsSerialFrame is the data-structure of this message
type _AmsSerialFrame struct {
	MagicCookie        uint16
	TransmitterAddress int8
	ReceiverAddress    int8
	FragmentNumber     int8
	Length             int8
	Userdata           AmsPacket
	Crc                uint16
}

var _ AmsSerialFrame = (*_AmsSerialFrame)(nil)

// NewAmsSerialFrame factory function for _AmsSerialFrame
func NewAmsSerialFrame(magicCookie uint16, transmitterAddress int8, receiverAddress int8, fragmentNumber int8, length int8, userdata AmsPacket, crc uint16) *_AmsSerialFrame {
	if userdata == nil {
		panic("userdata of type AmsPacket for AmsSerialFrame must not be nil")
	}
	return &_AmsSerialFrame{MagicCookie: magicCookie, TransmitterAddress: transmitterAddress, ReceiverAddress: receiverAddress, FragmentNumber: fragmentNumber, Length: length, Userdata: userdata, Crc: crc}
}

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

// AmsSerialFrameBuilder is a builder for AmsSerialFrame
type AmsSerialFrameBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(magicCookie uint16, transmitterAddress int8, receiverAddress int8, fragmentNumber int8, length int8, userdata AmsPacket, crc uint16) AmsSerialFrameBuilder
	// WithMagicCookie adds MagicCookie (property field)
	WithMagicCookie(uint16) AmsSerialFrameBuilder
	// WithTransmitterAddress adds TransmitterAddress (property field)
	WithTransmitterAddress(int8) AmsSerialFrameBuilder
	// WithReceiverAddress adds ReceiverAddress (property field)
	WithReceiverAddress(int8) AmsSerialFrameBuilder
	// WithFragmentNumber adds FragmentNumber (property field)
	WithFragmentNumber(int8) AmsSerialFrameBuilder
	// WithLength adds Length (property field)
	WithLength(int8) AmsSerialFrameBuilder
	// WithUserdata adds Userdata (property field)
	WithUserdata(AmsPacket) AmsSerialFrameBuilder
	// WithUserdataBuilder adds Userdata (property field) which is build by the builder
	WithUserdataBuilder(func(AmsPacketBuilder) AmsPacketBuilder) AmsSerialFrameBuilder
	// WithCrc adds Crc (property field)
	WithCrc(uint16) AmsSerialFrameBuilder
	// Build builds the AmsSerialFrame or returns an error if something is wrong
	Build() (AmsSerialFrame, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() AmsSerialFrame
}

// NewAmsSerialFrameBuilder() creates a AmsSerialFrameBuilder
func NewAmsSerialFrameBuilder() AmsSerialFrameBuilder {
	return &_AmsSerialFrameBuilder{_AmsSerialFrame: new(_AmsSerialFrame)}
}

type _AmsSerialFrameBuilder struct {
	*_AmsSerialFrame

	collectedErr []error
}

var _ (AmsSerialFrameBuilder) = (*_AmsSerialFrameBuilder)(nil)

func (b *_AmsSerialFrameBuilder) WithMandatoryFields(magicCookie uint16, transmitterAddress int8, receiverAddress int8, fragmentNumber int8, length int8, userdata AmsPacket, crc uint16) AmsSerialFrameBuilder {
	return b.WithMagicCookie(magicCookie).WithTransmitterAddress(transmitterAddress).WithReceiverAddress(receiverAddress).WithFragmentNumber(fragmentNumber).WithLength(length).WithUserdata(userdata).WithCrc(crc)
}

func (b *_AmsSerialFrameBuilder) WithMagicCookie(magicCookie uint16) AmsSerialFrameBuilder {
	b.MagicCookie = magicCookie
	return b
}

func (b *_AmsSerialFrameBuilder) WithTransmitterAddress(transmitterAddress int8) AmsSerialFrameBuilder {
	b.TransmitterAddress = transmitterAddress
	return b
}

func (b *_AmsSerialFrameBuilder) WithReceiverAddress(receiverAddress int8) AmsSerialFrameBuilder {
	b.ReceiverAddress = receiverAddress
	return b
}

func (b *_AmsSerialFrameBuilder) WithFragmentNumber(fragmentNumber int8) AmsSerialFrameBuilder {
	b.FragmentNumber = fragmentNumber
	return b
}

func (b *_AmsSerialFrameBuilder) WithLength(length int8) AmsSerialFrameBuilder {
	b.Length = length
	return b
}

func (b *_AmsSerialFrameBuilder) WithUserdata(userdata AmsPacket) AmsSerialFrameBuilder {
	b.Userdata = userdata
	return b
}

func (b *_AmsSerialFrameBuilder) WithUserdataBuilder(builderSupplier func(AmsPacketBuilder) AmsPacketBuilder) AmsSerialFrameBuilder {
	builder := builderSupplier(b.Userdata.CreateAmsPacketBuilder())
	var err error
	b.Userdata, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "AmsPacketBuilder failed"))
	}
	return b
}

func (b *_AmsSerialFrameBuilder) WithCrc(crc uint16) AmsSerialFrameBuilder {
	b.Crc = crc
	return b
}

func (b *_AmsSerialFrameBuilder) Build() (AmsSerialFrame, error) {
	if b.Userdata == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'userdata' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._AmsSerialFrame.deepCopy(), nil
}

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

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

// CreateAmsSerialFrameBuilder creates a AmsSerialFrameBuilder
func (b *_AmsSerialFrame) CreateAmsSerialFrameBuilder() AmsSerialFrameBuilder {
	if b == nil {
		return NewAmsSerialFrameBuilder()
	}
	return &_AmsSerialFrameBuilder{_AmsSerialFrame: b.deepCopy()}
}

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

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

func (m *_AmsSerialFrame) GetMagicCookie() uint16 {
	return m.MagicCookie
}

func (m *_AmsSerialFrame) GetTransmitterAddress() int8 {
	return m.TransmitterAddress
}

func (m *_AmsSerialFrame) GetReceiverAddress() int8 {
	return m.ReceiverAddress
}

func (m *_AmsSerialFrame) GetFragmentNumber() int8 {
	return m.FragmentNumber
}

func (m *_AmsSerialFrame) GetLength() int8 {
	return m.Length
}

func (m *_AmsSerialFrame) GetUserdata() AmsPacket {
	return m.Userdata
}

func (m *_AmsSerialFrame) GetCrc() uint16 {
	return m.Crc
}

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

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

func (m *_AmsSerialFrame) GetTypeName() string {
	return "AmsSerialFrame"
}

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

	// Simple field (magicCookie)
	lengthInBits += 16

	// Simple field (transmitterAddress)
	lengthInBits += 8

	// Simple field (receiverAddress)
	lengthInBits += 8

	// Simple field (fragmentNumber)
	lengthInBits += 8

	// Simple field (length)
	lengthInBits += 8

	// Simple field (userdata)
	lengthInBits += m.Userdata.GetLengthInBits(ctx)

	// Simple field (crc)
	lengthInBits += 16

	return lengthInBits
}

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

func AmsSerialFrameParse(ctx context.Context, theBytes []byte) (AmsSerialFrame, error) {
	return AmsSerialFrameParseWithBuffer(ctx, utils.NewReadBufferByteBased(theBytes))
}

func AmsSerialFrameParseWithBufferProducer() func(ctx context.Context, readBuffer utils.ReadBuffer) (AmsSerialFrame, error) {
	return func(ctx context.Context, readBuffer utils.ReadBuffer) (AmsSerialFrame, error) {
		return AmsSerialFrameParseWithBuffer(ctx, readBuffer)
	}
}

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

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

	magicCookie, err := ReadSimpleField(ctx, "magicCookie", ReadUnsignedShort(readBuffer, uint8(16)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'magicCookie' field"))
	}
	m.MagicCookie = magicCookie

	transmitterAddress, err := ReadSimpleField(ctx, "transmitterAddress", ReadSignedByte(readBuffer, uint8(8)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'transmitterAddress' field"))
	}
	m.TransmitterAddress = transmitterAddress

	receiverAddress, err := ReadSimpleField(ctx, "receiverAddress", ReadSignedByte(readBuffer, uint8(8)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'receiverAddress' field"))
	}
	m.ReceiverAddress = receiverAddress

	fragmentNumber, err := ReadSimpleField(ctx, "fragmentNumber", ReadSignedByte(readBuffer, uint8(8)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'fragmentNumber' field"))
	}
	m.FragmentNumber = fragmentNumber

	length, err := ReadSimpleField(ctx, "length", ReadSignedByte(readBuffer, uint8(8)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'length' field"))
	}
	m.Length = length

	userdata, err := ReadSimpleField[AmsPacket](ctx, "userdata", ReadComplex[AmsPacket](AmsPacketParseWithBuffer, readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'userdata' field"))
	}
	m.Userdata = userdata

	crc, err := ReadSimpleField(ctx, "crc", ReadUnsignedShort(readBuffer, uint8(16)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'crc' field"))
	}
	m.Crc = crc

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

	return m, nil
}

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

	if err := WriteSimpleField[uint16](ctx, "magicCookie", m.GetMagicCookie(), WriteUnsignedShort(writeBuffer, 16)); err != nil {
		return errors.Wrap(err, "Error serializing 'magicCookie' field")
	}

	if err := WriteSimpleField[int8](ctx, "transmitterAddress", m.GetTransmitterAddress(), WriteSignedByte(writeBuffer, 8)); err != nil {
		return errors.Wrap(err, "Error serializing 'transmitterAddress' field")
	}

	if err := WriteSimpleField[int8](ctx, "receiverAddress", m.GetReceiverAddress(), WriteSignedByte(writeBuffer, 8)); err != nil {
		return errors.Wrap(err, "Error serializing 'receiverAddress' field")
	}

	if err := WriteSimpleField[int8](ctx, "fragmentNumber", m.GetFragmentNumber(), WriteSignedByte(writeBuffer, 8)); err != nil {
		return errors.Wrap(err, "Error serializing 'fragmentNumber' field")
	}

	if err := WriteSimpleField[int8](ctx, "length", m.GetLength(), WriteSignedByte(writeBuffer, 8)); err != nil {
		return errors.Wrap(err, "Error serializing 'length' field")
	}

	if err := WriteSimpleField[AmsPacket](ctx, "userdata", m.GetUserdata(), WriteComplex[AmsPacket](writeBuffer)); err != nil {
		return errors.Wrap(err, "Error serializing 'userdata' field")
	}

	if err := WriteSimpleField[uint16](ctx, "crc", m.GetCrc(), WriteUnsignedShort(writeBuffer, 16)); err != nil {
		return errors.Wrap(err, "Error serializing 'crc' field")
	}

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

func (m *_AmsSerialFrame) IsAmsSerialFrame() {}

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

func (m *_AmsSerialFrame) deepCopy() *_AmsSerialFrame {
	if m == nil {
		return nil
	}
	_AmsSerialFrameCopy := &_AmsSerialFrame{
		m.MagicCookie,
		m.TransmitterAddress,
		m.ReceiverAddress,
		m.FragmentNumber,
		m.Length,
		utils.DeepCopy[AmsPacket](m.Userdata),
		m.Crc,
	}
	return _AmsSerialFrameCopy
}

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