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

// NetworkRoute is the corresponding interface of NetworkRoute
type NetworkRoute interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	// GetNetworkPCI returns NetworkPCI (property field)
	GetNetworkPCI() NetworkProtocolControlInformation
	// GetAdditionalBridgeAddresses returns AdditionalBridgeAddresses (property field)
	GetAdditionalBridgeAddresses() []BridgeAddress
	// IsNetworkRoute is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsNetworkRoute()
	// CreateBuilder creates a NetworkRouteBuilder
	CreateNetworkRouteBuilder() NetworkRouteBuilder
}

// _NetworkRoute is the data-structure of this message
type _NetworkRoute struct {
	NetworkPCI                NetworkProtocolControlInformation
	AdditionalBridgeAddresses []BridgeAddress
}

var _ NetworkRoute = (*_NetworkRoute)(nil)

// NewNetworkRoute factory function for _NetworkRoute
func NewNetworkRoute(networkPCI NetworkProtocolControlInformation, additionalBridgeAddresses []BridgeAddress) *_NetworkRoute {
	if networkPCI == nil {
		panic("networkPCI of type NetworkProtocolControlInformation for NetworkRoute must not be nil")
	}
	return &_NetworkRoute{NetworkPCI: networkPCI, AdditionalBridgeAddresses: additionalBridgeAddresses}
}

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

// NetworkRouteBuilder is a builder for NetworkRoute
type NetworkRouteBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(networkPCI NetworkProtocolControlInformation, additionalBridgeAddresses []BridgeAddress) NetworkRouteBuilder
	// WithNetworkPCI adds NetworkPCI (property field)
	WithNetworkPCI(NetworkProtocolControlInformation) NetworkRouteBuilder
	// WithNetworkPCIBuilder adds NetworkPCI (property field) which is build by the builder
	WithNetworkPCIBuilder(func(NetworkProtocolControlInformationBuilder) NetworkProtocolControlInformationBuilder) NetworkRouteBuilder
	// WithAdditionalBridgeAddresses adds AdditionalBridgeAddresses (property field)
	WithAdditionalBridgeAddresses(...BridgeAddress) NetworkRouteBuilder
	// Build builds the NetworkRoute or returns an error if something is wrong
	Build() (NetworkRoute, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() NetworkRoute
}

// NewNetworkRouteBuilder() creates a NetworkRouteBuilder
func NewNetworkRouteBuilder() NetworkRouteBuilder {
	return &_NetworkRouteBuilder{_NetworkRoute: new(_NetworkRoute)}
}

type _NetworkRouteBuilder struct {
	*_NetworkRoute

	collectedErr []error
}

var _ (NetworkRouteBuilder) = (*_NetworkRouteBuilder)(nil)

func (b *_NetworkRouteBuilder) WithMandatoryFields(networkPCI NetworkProtocolControlInformation, additionalBridgeAddresses []BridgeAddress) NetworkRouteBuilder {
	return b.WithNetworkPCI(networkPCI).WithAdditionalBridgeAddresses(additionalBridgeAddresses...)
}

func (b *_NetworkRouteBuilder) WithNetworkPCI(networkPCI NetworkProtocolControlInformation) NetworkRouteBuilder {
	b.NetworkPCI = networkPCI
	return b
}

func (b *_NetworkRouteBuilder) WithNetworkPCIBuilder(builderSupplier func(NetworkProtocolControlInformationBuilder) NetworkProtocolControlInformationBuilder) NetworkRouteBuilder {
	builder := builderSupplier(b.NetworkPCI.CreateNetworkProtocolControlInformationBuilder())
	var err error
	b.NetworkPCI, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "NetworkProtocolControlInformationBuilder failed"))
	}
	return b
}

func (b *_NetworkRouteBuilder) WithAdditionalBridgeAddresses(additionalBridgeAddresses ...BridgeAddress) NetworkRouteBuilder {
	b.AdditionalBridgeAddresses = additionalBridgeAddresses
	return b
}

func (b *_NetworkRouteBuilder) Build() (NetworkRoute, error) {
	if b.NetworkPCI == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'networkPCI' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._NetworkRoute.deepCopy(), nil
}

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

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

// CreateNetworkRouteBuilder creates a NetworkRouteBuilder
func (b *_NetworkRoute) CreateNetworkRouteBuilder() NetworkRouteBuilder {
	if b == nil {
		return NewNetworkRouteBuilder()
	}
	return &_NetworkRouteBuilder{_NetworkRoute: b.deepCopy()}
}

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

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

func (m *_NetworkRoute) GetNetworkPCI() NetworkProtocolControlInformation {
	return m.NetworkPCI
}

func (m *_NetworkRoute) GetAdditionalBridgeAddresses() []BridgeAddress {
	return m.AdditionalBridgeAddresses
}

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

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

func (m *_NetworkRoute) GetTypeName() string {
	return "NetworkRoute"
}

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

	// Simple field (networkPCI)
	lengthInBits += m.NetworkPCI.GetLengthInBits(ctx)

	// Array field
	if len(m.AdditionalBridgeAddresses) > 0 {
		for _curItem, element := range m.AdditionalBridgeAddresses {
			arrayCtx := utils.CreateArrayContext(ctx, len(m.AdditionalBridgeAddresses), _curItem)
			lengthInBits += element.GetLengthInBits(arrayCtx)
		}
	}

	return lengthInBits
}

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

func NetworkRouteParse(ctx context.Context, theBytes []byte) (NetworkRoute, error) {
	return NetworkRouteParseWithBuffer(ctx, utils.NewReadBufferByteBased(theBytes))
}

func NetworkRouteParseWithBufferProducer() func(ctx context.Context, readBuffer utils.ReadBuffer) (NetworkRoute, error) {
	return func(ctx context.Context, readBuffer utils.ReadBuffer) (NetworkRoute, error) {
		return NetworkRouteParseWithBuffer(ctx, readBuffer)
	}
}

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

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

	networkPCI, err := ReadSimpleField[NetworkProtocolControlInformation](ctx, "networkPCI", ReadComplex[NetworkProtocolControlInformation](NetworkProtocolControlInformationParseWithBuffer, readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'networkPCI' field"))
	}
	m.NetworkPCI = networkPCI

	additionalBridgeAddresses, err := ReadCountArrayField[BridgeAddress](ctx, "additionalBridgeAddresses", ReadComplex[BridgeAddress](BridgeAddressParseWithBuffer, readBuffer), uint64(int32(networkPCI.GetStackDepth())-int32(int32(1))))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'additionalBridgeAddresses' field"))
	}
	m.AdditionalBridgeAddresses = additionalBridgeAddresses

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

	return m, nil
}

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

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

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

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

func (m *_NetworkRoute) IsNetworkRoute() {}

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

func (m *_NetworkRoute) deepCopy() *_NetworkRoute {
	if m == nil {
		return nil
	}
	_NetworkRouteCopy := &_NetworkRoute{
		utils.DeepCopy[NetworkProtocolControlInformation](m.NetworkPCI),
		utils.DeepCopySlice[BridgeAddress, BridgeAddress](m.AdditionalBridgeAddresses),
	}
	return _NetworkRouteCopy
}

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