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

// HPAIDiscoveryEndpoint is the corresponding interface of HPAIDiscoveryEndpoint
type HPAIDiscoveryEndpoint interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	// GetHostProtocolCode returns HostProtocolCode (property field)
	GetHostProtocolCode() HostProtocolCode
	// GetIpAddress returns IpAddress (property field)
	GetIpAddress() IPAddress
	// GetIpPort returns IpPort (property field)
	GetIpPort() uint16
	// IsHPAIDiscoveryEndpoint is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsHPAIDiscoveryEndpoint()
	// CreateBuilder creates a HPAIDiscoveryEndpointBuilder
	CreateHPAIDiscoveryEndpointBuilder() HPAIDiscoveryEndpointBuilder
}

// _HPAIDiscoveryEndpoint is the data-structure of this message
type _HPAIDiscoveryEndpoint struct {
	HostProtocolCode HostProtocolCode
	IpAddress        IPAddress
	IpPort           uint16
}

var _ HPAIDiscoveryEndpoint = (*_HPAIDiscoveryEndpoint)(nil)

// NewHPAIDiscoveryEndpoint factory function for _HPAIDiscoveryEndpoint
func NewHPAIDiscoveryEndpoint(hostProtocolCode HostProtocolCode, ipAddress IPAddress, ipPort uint16) *_HPAIDiscoveryEndpoint {
	if ipAddress == nil {
		panic("ipAddress of type IPAddress for HPAIDiscoveryEndpoint must not be nil")
	}
	return &_HPAIDiscoveryEndpoint{HostProtocolCode: hostProtocolCode, IpAddress: ipAddress, IpPort: ipPort}
}

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

// HPAIDiscoveryEndpointBuilder is a builder for HPAIDiscoveryEndpoint
type HPAIDiscoveryEndpointBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(hostProtocolCode HostProtocolCode, ipAddress IPAddress, ipPort uint16) HPAIDiscoveryEndpointBuilder
	// WithHostProtocolCode adds HostProtocolCode (property field)
	WithHostProtocolCode(HostProtocolCode) HPAIDiscoveryEndpointBuilder
	// WithIpAddress adds IpAddress (property field)
	WithIpAddress(IPAddress) HPAIDiscoveryEndpointBuilder
	// WithIpAddressBuilder adds IpAddress (property field) which is build by the builder
	WithIpAddressBuilder(func(IPAddressBuilder) IPAddressBuilder) HPAIDiscoveryEndpointBuilder
	// WithIpPort adds IpPort (property field)
	WithIpPort(uint16) HPAIDiscoveryEndpointBuilder
	// Build builds the HPAIDiscoveryEndpoint or returns an error if something is wrong
	Build() (HPAIDiscoveryEndpoint, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() HPAIDiscoveryEndpoint
}

// NewHPAIDiscoveryEndpointBuilder() creates a HPAIDiscoveryEndpointBuilder
func NewHPAIDiscoveryEndpointBuilder() HPAIDiscoveryEndpointBuilder {
	return &_HPAIDiscoveryEndpointBuilder{_HPAIDiscoveryEndpoint: new(_HPAIDiscoveryEndpoint)}
}

type _HPAIDiscoveryEndpointBuilder struct {
	*_HPAIDiscoveryEndpoint

	err *utils.MultiError
}

var _ (HPAIDiscoveryEndpointBuilder) = (*_HPAIDiscoveryEndpointBuilder)(nil)

func (b *_HPAIDiscoveryEndpointBuilder) WithMandatoryFields(hostProtocolCode HostProtocolCode, ipAddress IPAddress, ipPort uint16) HPAIDiscoveryEndpointBuilder {
	return b.WithHostProtocolCode(hostProtocolCode).WithIpAddress(ipAddress).WithIpPort(ipPort)
}

func (b *_HPAIDiscoveryEndpointBuilder) WithHostProtocolCode(hostProtocolCode HostProtocolCode) HPAIDiscoveryEndpointBuilder {
	b.HostProtocolCode = hostProtocolCode
	return b
}

func (b *_HPAIDiscoveryEndpointBuilder) WithIpAddress(ipAddress IPAddress) HPAIDiscoveryEndpointBuilder {
	b.IpAddress = ipAddress
	return b
}

func (b *_HPAIDiscoveryEndpointBuilder) WithIpAddressBuilder(builderSupplier func(IPAddressBuilder) IPAddressBuilder) HPAIDiscoveryEndpointBuilder {
	builder := builderSupplier(b.IpAddress.CreateIPAddressBuilder())
	var err error
	b.IpAddress, err = builder.Build()
	if err != nil {
		if b.err == nil {
			b.err = &utils.MultiError{MainError: errors.New("sub builder failed")}
		}
		b.err.Append(errors.Wrap(err, "IPAddressBuilder failed"))
	}
	return b
}

func (b *_HPAIDiscoveryEndpointBuilder) WithIpPort(ipPort uint16) HPAIDiscoveryEndpointBuilder {
	b.IpPort = ipPort
	return b
}

func (b *_HPAIDiscoveryEndpointBuilder) Build() (HPAIDiscoveryEndpoint, error) {
	if b.IpAddress == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'ipAddress' not set"))
	}
	if b.err != nil {
		return nil, errors.Wrap(b.err, "error occurred during build")
	}
	return b._HPAIDiscoveryEndpoint.deepCopy(), nil
}

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

func (b *_HPAIDiscoveryEndpointBuilder) DeepCopy() any {
	_copy := b.CreateHPAIDiscoveryEndpointBuilder().(*_HPAIDiscoveryEndpointBuilder)
	if b.err != nil {
		_copy.err = b.err.DeepCopy().(*utils.MultiError)
	}
	return _copy
}

// CreateHPAIDiscoveryEndpointBuilder creates a HPAIDiscoveryEndpointBuilder
func (b *_HPAIDiscoveryEndpoint) CreateHPAIDiscoveryEndpointBuilder() HPAIDiscoveryEndpointBuilder {
	if b == nil {
		return NewHPAIDiscoveryEndpointBuilder()
	}
	return &_HPAIDiscoveryEndpointBuilder{_HPAIDiscoveryEndpoint: b.deepCopy()}
}

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

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

func (m *_HPAIDiscoveryEndpoint) GetHostProtocolCode() HostProtocolCode {
	return m.HostProtocolCode
}

func (m *_HPAIDiscoveryEndpoint) GetIpAddress() IPAddress {
	return m.IpAddress
}

func (m *_HPAIDiscoveryEndpoint) GetIpPort() uint16 {
	return m.IpPort
}

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

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

func (m *_HPAIDiscoveryEndpoint) GetTypeName() string {
	return "HPAIDiscoveryEndpoint"
}

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

	// Implicit Field (structureLength)
	lengthInBits += 8

	// Simple field (hostProtocolCode)
	lengthInBits += 8

	// Simple field (ipAddress)
	lengthInBits += m.IpAddress.GetLengthInBits(ctx)

	// Simple field (ipPort)
	lengthInBits += 16

	return lengthInBits
}

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

func HPAIDiscoveryEndpointParse(ctx context.Context, theBytes []byte) (HPAIDiscoveryEndpoint, error) {
	return HPAIDiscoveryEndpointParseWithBuffer(ctx, utils.NewReadBufferByteBased(theBytes))
}

func HPAIDiscoveryEndpointParseWithBufferProducer() func(ctx context.Context, readBuffer utils.ReadBuffer) (HPAIDiscoveryEndpoint, error) {
	return func(ctx context.Context, readBuffer utils.ReadBuffer) (HPAIDiscoveryEndpoint, error) {
		return HPAIDiscoveryEndpointParseWithBuffer(ctx, readBuffer)
	}
}

func HPAIDiscoveryEndpointParseWithBuffer(ctx context.Context, readBuffer utils.ReadBuffer) (HPAIDiscoveryEndpoint, error) {
	v, err := (&_HPAIDiscoveryEndpoint{}).parse(ctx, readBuffer)
	if err != nil {
		return nil, err
	}
	return v, nil
}

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

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

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

	ipAddress, err := ReadSimpleField[IPAddress](ctx, "ipAddress", ReadComplex[IPAddress](IPAddressParseWithBuffer, readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'ipAddress' field"))
	}
	m.IpAddress = ipAddress

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

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

	return m, nil
}

func (m *_HPAIDiscoveryEndpoint) 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 *_HPAIDiscoveryEndpoint) SerializeWithWriteBuffer(ctx context.Context, writeBuffer utils.WriteBuffer) error {
	positionAware := writeBuffer
	_ = positionAware
	log := zerolog.Ctx(ctx)
	_ = log
	if pushErr := writeBuffer.PushContext("HPAIDiscoveryEndpoint"); pushErr != nil {
		return errors.Wrap(pushErr, "Error pushing for HPAIDiscoveryEndpoint")
	}
	structureLength := uint8(uint8(m.GetLengthInBytes(ctx)))
	if err := WriteImplicitField(ctx, "structureLength", structureLength, WriteUnsignedByte(writeBuffer, 8)); err != nil {
		return errors.Wrap(err, "Error serializing 'structureLength' field")
	}

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

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

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

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

func (m *_HPAIDiscoveryEndpoint) IsHPAIDiscoveryEndpoint() {}

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

func (m *_HPAIDiscoveryEndpoint) deepCopy() *_HPAIDiscoveryEndpoint {
	if m == nil {
		return nil
	}
	_HPAIDiscoveryEndpointCopy := &_HPAIDiscoveryEndpoint{
		m.HostProtocolCode,
		utils.DeepCopy[IPAddress](m.IpAddress),
		m.IpPort,
	}
	return _HPAIDiscoveryEndpointCopy
}

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