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

// S7AddressAny is the corresponding interface of S7AddressAny
type S7AddressAny interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	S7Address
	// GetTransportSize returns TransportSize (property field)
	GetTransportSize() TransportSize
	// GetNumberOfElements returns NumberOfElements (property field)
	GetNumberOfElements() uint16
	// GetDbNumber returns DbNumber (property field)
	GetDbNumber() uint16
	// GetArea returns Area (property field)
	GetArea() MemoryArea
	// GetByteAddress returns ByteAddress (property field)
	GetByteAddress() uint16
	// GetBitAddress returns BitAddress (property field)
	GetBitAddress() uint8
	// IsS7AddressAny is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsS7AddressAny()
	// CreateBuilder creates a S7AddressAnyBuilder
	CreateS7AddressAnyBuilder() S7AddressAnyBuilder
}

// _S7AddressAny is the data-structure of this message
type _S7AddressAny struct {
	S7AddressContract
	TransportSize    TransportSize
	NumberOfElements uint16
	DbNumber         uint16
	Area             MemoryArea
	ByteAddress      uint16
	BitAddress       uint8
	// Reserved Fields
	reservedField0 *uint8
}

var _ S7AddressAny = (*_S7AddressAny)(nil)
var _ S7AddressRequirements = (*_S7AddressAny)(nil)

// NewS7AddressAny factory function for _S7AddressAny
func NewS7AddressAny(transportSize TransportSize, numberOfElements uint16, dbNumber uint16, area MemoryArea, byteAddress uint16, bitAddress uint8) *_S7AddressAny {
	_result := &_S7AddressAny{
		S7AddressContract: NewS7Address(),
		TransportSize:     transportSize,
		NumberOfElements:  numberOfElements,
		DbNumber:          dbNumber,
		Area:              area,
		ByteAddress:       byteAddress,
		BitAddress:        bitAddress,
	}
	_result.S7AddressContract.(*_S7Address)._SubType = _result
	return _result
}

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

// S7AddressAnyBuilder is a builder for S7AddressAny
type S7AddressAnyBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(transportSize TransportSize, numberOfElements uint16, dbNumber uint16, area MemoryArea, byteAddress uint16, bitAddress uint8) S7AddressAnyBuilder
	// WithTransportSize adds TransportSize (property field)
	WithTransportSize(TransportSize) S7AddressAnyBuilder
	// WithNumberOfElements adds NumberOfElements (property field)
	WithNumberOfElements(uint16) S7AddressAnyBuilder
	// WithDbNumber adds DbNumber (property field)
	WithDbNumber(uint16) S7AddressAnyBuilder
	// WithArea adds Area (property field)
	WithArea(MemoryArea) S7AddressAnyBuilder
	// WithByteAddress adds ByteAddress (property field)
	WithByteAddress(uint16) S7AddressAnyBuilder
	// WithBitAddress adds BitAddress (property field)
	WithBitAddress(uint8) S7AddressAnyBuilder
	// Done is used to finish work on this child and return (or create one if none) to the parent builder
	Done() S7AddressBuilder
	// Build builds the S7AddressAny or returns an error if something is wrong
	Build() (S7AddressAny, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() S7AddressAny
}

// NewS7AddressAnyBuilder() creates a S7AddressAnyBuilder
func NewS7AddressAnyBuilder() S7AddressAnyBuilder {
	return &_S7AddressAnyBuilder{_S7AddressAny: new(_S7AddressAny)}
}

type _S7AddressAnyBuilder struct {
	*_S7AddressAny

	parentBuilder *_S7AddressBuilder

	collectedErr []error
}

var _ (S7AddressAnyBuilder) = (*_S7AddressAnyBuilder)(nil)

func (b *_S7AddressAnyBuilder) setParent(contract S7AddressContract) {
	b.S7AddressContract = contract
	contract.(*_S7Address)._SubType = b._S7AddressAny
}

func (b *_S7AddressAnyBuilder) WithMandatoryFields(transportSize TransportSize, numberOfElements uint16, dbNumber uint16, area MemoryArea, byteAddress uint16, bitAddress uint8) S7AddressAnyBuilder {
	return b.WithTransportSize(transportSize).WithNumberOfElements(numberOfElements).WithDbNumber(dbNumber).WithArea(area).WithByteAddress(byteAddress).WithBitAddress(bitAddress)
}

func (b *_S7AddressAnyBuilder) WithTransportSize(transportSize TransportSize) S7AddressAnyBuilder {
	b.TransportSize = transportSize
	return b
}

func (b *_S7AddressAnyBuilder) WithNumberOfElements(numberOfElements uint16) S7AddressAnyBuilder {
	b.NumberOfElements = numberOfElements
	return b
}

func (b *_S7AddressAnyBuilder) WithDbNumber(dbNumber uint16) S7AddressAnyBuilder {
	b.DbNumber = dbNumber
	return b
}

func (b *_S7AddressAnyBuilder) WithArea(area MemoryArea) S7AddressAnyBuilder {
	b.Area = area
	return b
}

func (b *_S7AddressAnyBuilder) WithByteAddress(byteAddress uint16) S7AddressAnyBuilder {
	b.ByteAddress = byteAddress
	return b
}

func (b *_S7AddressAnyBuilder) WithBitAddress(bitAddress uint8) S7AddressAnyBuilder {
	b.BitAddress = bitAddress
	return b
}

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

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

func (b *_S7AddressAnyBuilder) Done() S7AddressBuilder {
	if b.parentBuilder == nil {
		b.parentBuilder = NewS7AddressBuilder().(*_S7AddressBuilder)
	}
	return b.parentBuilder
}

func (b *_S7AddressAnyBuilder) buildForS7Address() (S7Address, error) {
	return b.Build()
}

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

// CreateS7AddressAnyBuilder creates a S7AddressAnyBuilder
func (b *_S7AddressAny) CreateS7AddressAnyBuilder() S7AddressAnyBuilder {
	if b == nil {
		return NewS7AddressAnyBuilder()
	}
	return &_S7AddressAnyBuilder{_S7AddressAny: b.deepCopy()}
}

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

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

func (m *_S7AddressAny) GetAddressType() uint8 {
	return 0x10
}

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

func (m *_S7AddressAny) GetParent() S7AddressContract {
	return m.S7AddressContract
}

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

func (m *_S7AddressAny) GetTransportSize() TransportSize {
	return m.TransportSize
}

func (m *_S7AddressAny) GetNumberOfElements() uint16 {
	return m.NumberOfElements
}

func (m *_S7AddressAny) GetDbNumber() uint16 {
	return m.DbNumber
}

func (m *_S7AddressAny) GetArea() MemoryArea {
	return m.Area
}

func (m *_S7AddressAny) GetByteAddress() uint16 {
	return m.ByteAddress
}

func (m *_S7AddressAny) GetBitAddress() uint8 {
	return m.BitAddress
}

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

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

func (m *_S7AddressAny) GetTypeName() string {
	return "S7AddressAny"
}

func (m *_S7AddressAny) GetLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(m.S7AddressContract.(*_S7Address).getLengthInBits(ctx))

	// Enum Field (transportSize)
	lengthInBits += 8

	// Simple field (numberOfElements)
	lengthInBits += 16

	// Simple field (dbNumber)
	lengthInBits += 16

	// Simple field (area)
	lengthInBits += 8

	// Reserved Field (reserved)
	lengthInBits += 5

	// Simple field (byteAddress)
	lengthInBits += 16

	// Simple field (bitAddress)
	lengthInBits += 3

	return lengthInBits
}

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

func (m *_S7AddressAny) parse(ctx context.Context, readBuffer utils.ReadBuffer, parent *_S7Address) (__s7AddressAny S7AddressAny, err error) {
	m.S7AddressContract = parent
	parent._SubType = m
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("S7AddressAny"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for S7AddressAny")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

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

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

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

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

	reservedField0, err := ReadReservedField(ctx, "reserved", ReadUnsignedByte(readBuffer, uint8(5)), uint8(0x00))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing reserved field"))
	}
	m.reservedField0 = reservedField0

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

	bitAddress, err := ReadSimpleField(ctx, "bitAddress", ReadUnsignedByte(readBuffer, uint8(3)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'bitAddress' field"))
	}
	m.BitAddress = bitAddress

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

	return m, nil
}

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

		if err := WriteEnumField(ctx, "transportSize", "TransportSize", m.GetTransportSize(), WriteEnum[TransportSize, uint8](TransportSize.GetCode, TransportSize.PLC4XEnumName, WriteUnsignedByte(writeBuffer, 8))); err != nil {
			return errors.Wrap(err, "Error serializing 'transportSize' field")
		}

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

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

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

		if err := WriteReservedField[uint8](ctx, "reserved", uint8(0x00), WriteUnsignedByte(writeBuffer, 5)); err != nil {
			return errors.Wrap(err, "Error serializing 'reserved' field number 1")
		}

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

		if err := WriteSimpleField[uint8](ctx, "bitAddress", m.GetBitAddress(), WriteUnsignedByte(writeBuffer, 3)); err != nil {
			return errors.Wrap(err, "Error serializing 'bitAddress' field")
		}

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

func (m *_S7AddressAny) IsS7AddressAny() {}

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

func (m *_S7AddressAny) deepCopy() *_S7AddressAny {
	if m == nil {
		return nil
	}
	_S7AddressAnyCopy := &_S7AddressAny{
		m.S7AddressContract.(*_S7Address).deepCopy(),
		m.TransportSize,
		m.NumberOfElements,
		m.DbNumber,
		m.Area,
		m.ByteAddress,
		m.BitAddress,
		m.reservedField0,
	}
	_S7AddressAnyCopy.S7AddressContract.(*_S7Address)._SubType = m
	return _S7AddressAnyCopy
}

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