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

// GetEndpointsResponse is the corresponding interface of GetEndpointsResponse
type GetEndpointsResponse interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetResponseHeader returns ResponseHeader (property field)
	GetResponseHeader() ResponseHeader
	// GetEndpoints returns Endpoints (property field)
	GetEndpoints() []EndpointDescription
	// IsGetEndpointsResponse is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsGetEndpointsResponse()
	// CreateBuilder creates a GetEndpointsResponseBuilder
	CreateGetEndpointsResponseBuilder() GetEndpointsResponseBuilder
}

// _GetEndpointsResponse is the data-structure of this message
type _GetEndpointsResponse struct {
	ExtensionObjectDefinitionContract
	ResponseHeader ResponseHeader
	Endpoints      []EndpointDescription
}

var _ GetEndpointsResponse = (*_GetEndpointsResponse)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_GetEndpointsResponse)(nil)

// NewGetEndpointsResponse factory function for _GetEndpointsResponse
func NewGetEndpointsResponse(responseHeader ResponseHeader, endpoints []EndpointDescription) *_GetEndpointsResponse {
	if responseHeader == nil {
		panic("responseHeader of type ResponseHeader for GetEndpointsResponse must not be nil")
	}
	_result := &_GetEndpointsResponse{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		ResponseHeader:                    responseHeader,
		Endpoints:                         endpoints,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// GetEndpointsResponseBuilder is a builder for GetEndpointsResponse
type GetEndpointsResponseBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(responseHeader ResponseHeader, endpoints []EndpointDescription) GetEndpointsResponseBuilder
	// WithResponseHeader adds ResponseHeader (property field)
	WithResponseHeader(ResponseHeader) GetEndpointsResponseBuilder
	// WithResponseHeaderBuilder adds ResponseHeader (property field) which is build by the builder
	WithResponseHeaderBuilder(func(ResponseHeaderBuilder) ResponseHeaderBuilder) GetEndpointsResponseBuilder
	// WithEndpoints adds Endpoints (property field)
	WithEndpoints(...EndpointDescription) GetEndpointsResponseBuilder
	// Done is used to finish work on this child and return (or create one if none) to the parent builder
	Done() ExtensionObjectDefinitionBuilder
	// Build builds the GetEndpointsResponse or returns an error if something is wrong
	Build() (GetEndpointsResponse, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() GetEndpointsResponse
}

// NewGetEndpointsResponseBuilder() creates a GetEndpointsResponseBuilder
func NewGetEndpointsResponseBuilder() GetEndpointsResponseBuilder {
	return &_GetEndpointsResponseBuilder{_GetEndpointsResponse: new(_GetEndpointsResponse)}
}

type _GetEndpointsResponseBuilder struct {
	*_GetEndpointsResponse

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (GetEndpointsResponseBuilder) = (*_GetEndpointsResponseBuilder)(nil)

func (b *_GetEndpointsResponseBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._GetEndpointsResponse
}

func (b *_GetEndpointsResponseBuilder) WithMandatoryFields(responseHeader ResponseHeader, endpoints []EndpointDescription) GetEndpointsResponseBuilder {
	return b.WithResponseHeader(responseHeader).WithEndpoints(endpoints...)
}

func (b *_GetEndpointsResponseBuilder) WithResponseHeader(responseHeader ResponseHeader) GetEndpointsResponseBuilder {
	b.ResponseHeader = responseHeader
	return b
}

func (b *_GetEndpointsResponseBuilder) WithResponseHeaderBuilder(builderSupplier func(ResponseHeaderBuilder) ResponseHeaderBuilder) GetEndpointsResponseBuilder {
	builder := builderSupplier(b.ResponseHeader.CreateResponseHeaderBuilder())
	var err error
	b.ResponseHeader, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "ResponseHeaderBuilder failed"))
	}
	return b
}

func (b *_GetEndpointsResponseBuilder) WithEndpoints(endpoints ...EndpointDescription) GetEndpointsResponseBuilder {
	b.Endpoints = endpoints
	return b
}

func (b *_GetEndpointsResponseBuilder) Build() (GetEndpointsResponse, error) {
	if b.ResponseHeader == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'responseHeader' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._GetEndpointsResponse.deepCopy(), nil
}

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

func (b *_GetEndpointsResponseBuilder) Done() ExtensionObjectDefinitionBuilder {
	if b.parentBuilder == nil {
		b.parentBuilder = NewExtensionObjectDefinitionBuilder().(*_ExtensionObjectDefinitionBuilder)
	}
	return b.parentBuilder
}

func (b *_GetEndpointsResponseBuilder) buildForExtensionObjectDefinition() (ExtensionObjectDefinition, error) {
	return b.Build()
}

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

// CreateGetEndpointsResponseBuilder creates a GetEndpointsResponseBuilder
func (b *_GetEndpointsResponse) CreateGetEndpointsResponseBuilder() GetEndpointsResponseBuilder {
	if b == nil {
		return NewGetEndpointsResponseBuilder()
	}
	return &_GetEndpointsResponseBuilder{_GetEndpointsResponse: b.deepCopy()}
}

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

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

func (m *_GetEndpointsResponse) GetExtensionId() int32 {
	return int32(431)
}

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

func (m *_GetEndpointsResponse) GetParent() ExtensionObjectDefinitionContract {
	return m.ExtensionObjectDefinitionContract
}

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

func (m *_GetEndpointsResponse) GetResponseHeader() ResponseHeader {
	return m.ResponseHeader
}

func (m *_GetEndpointsResponse) GetEndpoints() []EndpointDescription {
	return m.Endpoints
}

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

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

func (m *_GetEndpointsResponse) GetTypeName() string {
	return "GetEndpointsResponse"
}

func (m *_GetEndpointsResponse) GetLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).getLengthInBits(ctx))

	// Simple field (responseHeader)
	lengthInBits += m.ResponseHeader.GetLengthInBits(ctx)

	// Implicit Field (noOfEndpoints)
	lengthInBits += 32

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

	return lengthInBits
}

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

func (m *_GetEndpointsResponse) parse(ctx context.Context, readBuffer utils.ReadBuffer, parent *_ExtensionObjectDefinition, extensionId int32) (__getEndpointsResponse GetEndpointsResponse, err error) {
	m.ExtensionObjectDefinitionContract = parent
	parent._SubType = m
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("GetEndpointsResponse"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for GetEndpointsResponse")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

	responseHeader, err := ReadSimpleField[ResponseHeader](ctx, "responseHeader", ReadComplex[ResponseHeader](ExtensionObjectDefinitionParseWithBufferProducer[ResponseHeader]((int32)(int32(394))), readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'responseHeader' field"))
	}
	m.ResponseHeader = responseHeader

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

	endpoints, err := ReadCountArrayField[EndpointDescription](ctx, "endpoints", ReadComplex[EndpointDescription](ExtensionObjectDefinitionParseWithBufferProducer[EndpointDescription]((int32)(int32(314))), readBuffer), uint64(noOfEndpoints))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'endpoints' field"))
	}
	m.Endpoints = endpoints

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

	return m, nil
}

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

		if err := WriteSimpleField[ResponseHeader](ctx, "responseHeader", m.GetResponseHeader(), WriteComplex[ResponseHeader](writeBuffer)); err != nil {
			return errors.Wrap(err, "Error serializing 'responseHeader' field")
		}
		noOfEndpoints := int32(utils.InlineIf(bool((m.GetEndpoints()) == (nil)), func() any { return int32(-(int32(1))) }, func() any { return int32(int32(len(m.GetEndpoints()))) }).(int32))
		if err := WriteImplicitField(ctx, "noOfEndpoints", noOfEndpoints, WriteSignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'noOfEndpoints' field")
		}

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

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

func (m *_GetEndpointsResponse) IsGetEndpointsResponse() {}

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

func (m *_GetEndpointsResponse) deepCopy() *_GetEndpointsResponse {
	if m == nil {
		return nil
	}
	_GetEndpointsResponseCopy := &_GetEndpointsResponse{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[ResponseHeader](m.ResponseHeader),
		utils.DeepCopySlice[EndpointDescription, EndpointDescription](m.Endpoints),
	}
	_GetEndpointsResponseCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _GetEndpointsResponseCopy
}

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