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

// SetTriggeringRequest is the corresponding interface of SetTriggeringRequest
type SetTriggeringRequest interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetRequestHeader returns RequestHeader (property field)
	GetRequestHeader() RequestHeader
	// GetSubscriptionId returns SubscriptionId (property field)
	GetSubscriptionId() uint32
	// GetTriggeringItemId returns TriggeringItemId (property field)
	GetTriggeringItemId() uint32
	// GetLinksToAdd returns LinksToAdd (property field)
	GetLinksToAdd() []uint32
	// GetLinksToRemove returns LinksToRemove (property field)
	GetLinksToRemove() []uint32
	// IsSetTriggeringRequest is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsSetTriggeringRequest()
	// CreateBuilder creates a SetTriggeringRequestBuilder
	CreateSetTriggeringRequestBuilder() SetTriggeringRequestBuilder
}

// _SetTriggeringRequest is the data-structure of this message
type _SetTriggeringRequest struct {
	ExtensionObjectDefinitionContract
	RequestHeader    RequestHeader
	SubscriptionId   uint32
	TriggeringItemId uint32
	LinksToAdd       []uint32
	LinksToRemove    []uint32
}

var _ SetTriggeringRequest = (*_SetTriggeringRequest)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_SetTriggeringRequest)(nil)

// NewSetTriggeringRequest factory function for _SetTriggeringRequest
func NewSetTriggeringRequest(requestHeader RequestHeader, subscriptionId uint32, triggeringItemId uint32, linksToAdd []uint32, linksToRemove []uint32) *_SetTriggeringRequest {
	if requestHeader == nil {
		panic("requestHeader of type RequestHeader for SetTriggeringRequest must not be nil")
	}
	_result := &_SetTriggeringRequest{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		RequestHeader:                     requestHeader,
		SubscriptionId:                    subscriptionId,
		TriggeringItemId:                  triggeringItemId,
		LinksToAdd:                        linksToAdd,
		LinksToRemove:                     linksToRemove,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// SetTriggeringRequestBuilder is a builder for SetTriggeringRequest
type SetTriggeringRequestBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(requestHeader RequestHeader, subscriptionId uint32, triggeringItemId uint32, linksToAdd []uint32, linksToRemove []uint32) SetTriggeringRequestBuilder
	// WithRequestHeader adds RequestHeader (property field)
	WithRequestHeader(RequestHeader) SetTriggeringRequestBuilder
	// WithRequestHeaderBuilder adds RequestHeader (property field) which is build by the builder
	WithRequestHeaderBuilder(func(RequestHeaderBuilder) RequestHeaderBuilder) SetTriggeringRequestBuilder
	// WithSubscriptionId adds SubscriptionId (property field)
	WithSubscriptionId(uint32) SetTriggeringRequestBuilder
	// WithTriggeringItemId adds TriggeringItemId (property field)
	WithTriggeringItemId(uint32) SetTriggeringRequestBuilder
	// WithLinksToAdd adds LinksToAdd (property field)
	WithLinksToAdd(...uint32) SetTriggeringRequestBuilder
	// WithLinksToRemove adds LinksToRemove (property field)
	WithLinksToRemove(...uint32) SetTriggeringRequestBuilder
	// 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 SetTriggeringRequest or returns an error if something is wrong
	Build() (SetTriggeringRequest, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() SetTriggeringRequest
}

// NewSetTriggeringRequestBuilder() creates a SetTriggeringRequestBuilder
func NewSetTriggeringRequestBuilder() SetTriggeringRequestBuilder {
	return &_SetTriggeringRequestBuilder{_SetTriggeringRequest: new(_SetTriggeringRequest)}
}

type _SetTriggeringRequestBuilder struct {
	*_SetTriggeringRequest

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (SetTriggeringRequestBuilder) = (*_SetTriggeringRequestBuilder)(nil)

func (b *_SetTriggeringRequestBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._SetTriggeringRequest
}

func (b *_SetTriggeringRequestBuilder) WithMandatoryFields(requestHeader RequestHeader, subscriptionId uint32, triggeringItemId uint32, linksToAdd []uint32, linksToRemove []uint32) SetTriggeringRequestBuilder {
	return b.WithRequestHeader(requestHeader).WithSubscriptionId(subscriptionId).WithTriggeringItemId(triggeringItemId).WithLinksToAdd(linksToAdd...).WithLinksToRemove(linksToRemove...)
}

func (b *_SetTriggeringRequestBuilder) WithRequestHeader(requestHeader RequestHeader) SetTriggeringRequestBuilder {
	b.RequestHeader = requestHeader
	return b
}

func (b *_SetTriggeringRequestBuilder) WithRequestHeaderBuilder(builderSupplier func(RequestHeaderBuilder) RequestHeaderBuilder) SetTriggeringRequestBuilder {
	builder := builderSupplier(b.RequestHeader.CreateRequestHeaderBuilder())
	var err error
	b.RequestHeader, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "RequestHeaderBuilder failed"))
	}
	return b
}

func (b *_SetTriggeringRequestBuilder) WithSubscriptionId(subscriptionId uint32) SetTriggeringRequestBuilder {
	b.SubscriptionId = subscriptionId
	return b
}

func (b *_SetTriggeringRequestBuilder) WithTriggeringItemId(triggeringItemId uint32) SetTriggeringRequestBuilder {
	b.TriggeringItemId = triggeringItemId
	return b
}

func (b *_SetTriggeringRequestBuilder) WithLinksToAdd(linksToAdd ...uint32) SetTriggeringRequestBuilder {
	b.LinksToAdd = linksToAdd
	return b
}

func (b *_SetTriggeringRequestBuilder) WithLinksToRemove(linksToRemove ...uint32) SetTriggeringRequestBuilder {
	b.LinksToRemove = linksToRemove
	return b
}

func (b *_SetTriggeringRequestBuilder) Build() (SetTriggeringRequest, error) {
	if b.RequestHeader == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'requestHeader' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._SetTriggeringRequest.deepCopy(), nil
}

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

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

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

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

// CreateSetTriggeringRequestBuilder creates a SetTriggeringRequestBuilder
func (b *_SetTriggeringRequest) CreateSetTriggeringRequestBuilder() SetTriggeringRequestBuilder {
	if b == nil {
		return NewSetTriggeringRequestBuilder()
	}
	return &_SetTriggeringRequestBuilder{_SetTriggeringRequest: b.deepCopy()}
}

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

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

func (m *_SetTriggeringRequest) GetExtensionId() int32 {
	return int32(775)
}

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

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

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

func (m *_SetTriggeringRequest) GetRequestHeader() RequestHeader {
	return m.RequestHeader
}

func (m *_SetTriggeringRequest) GetSubscriptionId() uint32 {
	return m.SubscriptionId
}

func (m *_SetTriggeringRequest) GetTriggeringItemId() uint32 {
	return m.TriggeringItemId
}

func (m *_SetTriggeringRequest) GetLinksToAdd() []uint32 {
	return m.LinksToAdd
}

func (m *_SetTriggeringRequest) GetLinksToRemove() []uint32 {
	return m.LinksToRemove
}

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

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

func (m *_SetTriggeringRequest) GetTypeName() string {
	return "SetTriggeringRequest"
}

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

	// Simple field (requestHeader)
	lengthInBits += m.RequestHeader.GetLengthInBits(ctx)

	// Simple field (subscriptionId)
	lengthInBits += 32

	// Simple field (triggeringItemId)
	lengthInBits += 32

	// Implicit Field (noOfLinksToAdd)
	lengthInBits += 32

	// Array field
	if len(m.LinksToAdd) > 0 {
		lengthInBits += 32 * uint16(len(m.LinksToAdd))
	}

	// Implicit Field (noOfLinksToRemove)
	lengthInBits += 32

	// Array field
	if len(m.LinksToRemove) > 0 {
		lengthInBits += 32 * uint16(len(m.LinksToRemove))
	}

	return lengthInBits
}

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

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

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

	subscriptionId, err := ReadSimpleField(ctx, "subscriptionId", ReadUnsignedInt(readBuffer, uint8(32)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'subscriptionId' field"))
	}
	m.SubscriptionId = subscriptionId

	triggeringItemId, err := ReadSimpleField(ctx, "triggeringItemId", ReadUnsignedInt(readBuffer, uint8(32)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'triggeringItemId' field"))
	}
	m.TriggeringItemId = triggeringItemId

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

	linksToAdd, err := ReadCountArrayField[uint32](ctx, "linksToAdd", ReadUnsignedInt(readBuffer, uint8(32)), uint64(noOfLinksToAdd))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'linksToAdd' field"))
	}
	m.LinksToAdd = linksToAdd

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

	linksToRemove, err := ReadCountArrayField[uint32](ctx, "linksToRemove", ReadUnsignedInt(readBuffer, uint8(32)), uint64(noOfLinksToRemove))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'linksToRemove' field"))
	}
	m.LinksToRemove = linksToRemove

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

	return m, nil
}

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

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

		if err := WriteSimpleField[uint32](ctx, "subscriptionId", m.GetSubscriptionId(), WriteUnsignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'subscriptionId' field")
		}

		if err := WriteSimpleField[uint32](ctx, "triggeringItemId", m.GetTriggeringItemId(), WriteUnsignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'triggeringItemId' field")
		}
		noOfLinksToAdd := int32(utils.InlineIf(bool((m.GetLinksToAdd()) == (nil)), func() any { return int32(-(int32(1))) }, func() any { return int32(int32(len(m.GetLinksToAdd()))) }).(int32))
		if err := WriteImplicitField(ctx, "noOfLinksToAdd", noOfLinksToAdd, WriteSignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'noOfLinksToAdd' field")
		}

		if err := WriteSimpleTypeArrayField(ctx, "linksToAdd", m.GetLinksToAdd(), WriteUnsignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'linksToAdd' field")
		}
		noOfLinksToRemove := int32(utils.InlineIf(bool((m.GetLinksToRemove()) == (nil)), func() any { return int32(-(int32(1))) }, func() any { return int32(int32(len(m.GetLinksToRemove()))) }).(int32))
		if err := WriteImplicitField(ctx, "noOfLinksToRemove", noOfLinksToRemove, WriteSignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'noOfLinksToRemove' field")
		}

		if err := WriteSimpleTypeArrayField(ctx, "linksToRemove", m.GetLinksToRemove(), WriteUnsignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'linksToRemove' field")
		}

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

func (m *_SetTriggeringRequest) IsSetTriggeringRequest() {}

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

func (m *_SetTriggeringRequest) deepCopy() *_SetTriggeringRequest {
	if m == nil {
		return nil
	}
	_SetTriggeringRequestCopy := &_SetTriggeringRequest{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[RequestHeader](m.RequestHeader),
		m.SubscriptionId,
		m.TriggeringItemId,
		utils.DeepCopySlice[uint32, uint32](m.LinksToAdd),
		utils.DeepCopySlice[uint32, uint32](m.LinksToRemove),
	}
	_SetTriggeringRequestCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _SetTriggeringRequestCopy
}

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