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

// SetTriggeringResponse is the corresponding interface of SetTriggeringResponse
type SetTriggeringResponse interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetResponseHeader returns ResponseHeader (property field)
	GetResponseHeader() ResponseHeader
	// GetAddResults returns AddResults (property field)
	GetAddResults() []StatusCode
	// GetAddDiagnosticInfos returns AddDiagnosticInfos (property field)
	GetAddDiagnosticInfos() []DiagnosticInfo
	// GetRemoveResults returns RemoveResults (property field)
	GetRemoveResults() []StatusCode
	// GetRemoveDiagnosticInfos returns RemoveDiagnosticInfos (property field)
	GetRemoveDiagnosticInfos() []DiagnosticInfo
	// IsSetTriggeringResponse is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsSetTriggeringResponse()
	// CreateBuilder creates a SetTriggeringResponseBuilder
	CreateSetTriggeringResponseBuilder() SetTriggeringResponseBuilder
}

// _SetTriggeringResponse is the data-structure of this message
type _SetTriggeringResponse struct {
	ExtensionObjectDefinitionContract
	ResponseHeader        ResponseHeader
	AddResults            []StatusCode
	AddDiagnosticInfos    []DiagnosticInfo
	RemoveResults         []StatusCode
	RemoveDiagnosticInfos []DiagnosticInfo
}

var _ SetTriggeringResponse = (*_SetTriggeringResponse)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_SetTriggeringResponse)(nil)

// NewSetTriggeringResponse factory function for _SetTriggeringResponse
func NewSetTriggeringResponse(responseHeader ResponseHeader, addResults []StatusCode, addDiagnosticInfos []DiagnosticInfo, removeResults []StatusCode, removeDiagnosticInfos []DiagnosticInfo) *_SetTriggeringResponse {
	if responseHeader == nil {
		panic("responseHeader of type ResponseHeader for SetTriggeringResponse must not be nil")
	}
	_result := &_SetTriggeringResponse{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		ResponseHeader:                    responseHeader,
		AddResults:                        addResults,
		AddDiagnosticInfos:                addDiagnosticInfos,
		RemoveResults:                     removeResults,
		RemoveDiagnosticInfos:             removeDiagnosticInfos,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// SetTriggeringResponseBuilder is a builder for SetTriggeringResponse
type SetTriggeringResponseBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(responseHeader ResponseHeader, addResults []StatusCode, addDiagnosticInfos []DiagnosticInfo, removeResults []StatusCode, removeDiagnosticInfos []DiagnosticInfo) SetTriggeringResponseBuilder
	// WithResponseHeader adds ResponseHeader (property field)
	WithResponseHeader(ResponseHeader) SetTriggeringResponseBuilder
	// WithResponseHeaderBuilder adds ResponseHeader (property field) which is build by the builder
	WithResponseHeaderBuilder(func(ResponseHeaderBuilder) ResponseHeaderBuilder) SetTriggeringResponseBuilder
	// WithAddResults adds AddResults (property field)
	WithAddResults(...StatusCode) SetTriggeringResponseBuilder
	// WithAddDiagnosticInfos adds AddDiagnosticInfos (property field)
	WithAddDiagnosticInfos(...DiagnosticInfo) SetTriggeringResponseBuilder
	// WithRemoveResults adds RemoveResults (property field)
	WithRemoveResults(...StatusCode) SetTriggeringResponseBuilder
	// WithRemoveDiagnosticInfos adds RemoveDiagnosticInfos (property field)
	WithRemoveDiagnosticInfos(...DiagnosticInfo) SetTriggeringResponseBuilder
	// 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 SetTriggeringResponse or returns an error if something is wrong
	Build() (SetTriggeringResponse, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() SetTriggeringResponse
}

// NewSetTriggeringResponseBuilder() creates a SetTriggeringResponseBuilder
func NewSetTriggeringResponseBuilder() SetTriggeringResponseBuilder {
	return &_SetTriggeringResponseBuilder{_SetTriggeringResponse: new(_SetTriggeringResponse)}
}

type _SetTriggeringResponseBuilder struct {
	*_SetTriggeringResponse

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (SetTriggeringResponseBuilder) = (*_SetTriggeringResponseBuilder)(nil)

func (b *_SetTriggeringResponseBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._SetTriggeringResponse
}

func (b *_SetTriggeringResponseBuilder) WithMandatoryFields(responseHeader ResponseHeader, addResults []StatusCode, addDiagnosticInfos []DiagnosticInfo, removeResults []StatusCode, removeDiagnosticInfos []DiagnosticInfo) SetTriggeringResponseBuilder {
	return b.WithResponseHeader(responseHeader).WithAddResults(addResults...).WithAddDiagnosticInfos(addDiagnosticInfos...).WithRemoveResults(removeResults...).WithRemoveDiagnosticInfos(removeDiagnosticInfos...)
}

func (b *_SetTriggeringResponseBuilder) WithResponseHeader(responseHeader ResponseHeader) SetTriggeringResponseBuilder {
	b.ResponseHeader = responseHeader
	return b
}

func (b *_SetTriggeringResponseBuilder) WithResponseHeaderBuilder(builderSupplier func(ResponseHeaderBuilder) ResponseHeaderBuilder) SetTriggeringResponseBuilder {
	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 *_SetTriggeringResponseBuilder) WithAddResults(addResults ...StatusCode) SetTriggeringResponseBuilder {
	b.AddResults = addResults
	return b
}

func (b *_SetTriggeringResponseBuilder) WithAddDiagnosticInfos(addDiagnosticInfos ...DiagnosticInfo) SetTriggeringResponseBuilder {
	b.AddDiagnosticInfos = addDiagnosticInfos
	return b
}

func (b *_SetTriggeringResponseBuilder) WithRemoveResults(removeResults ...StatusCode) SetTriggeringResponseBuilder {
	b.RemoveResults = removeResults
	return b
}

func (b *_SetTriggeringResponseBuilder) WithRemoveDiagnosticInfos(removeDiagnosticInfos ...DiagnosticInfo) SetTriggeringResponseBuilder {
	b.RemoveDiagnosticInfos = removeDiagnosticInfos
	return b
}

func (b *_SetTriggeringResponseBuilder) Build() (SetTriggeringResponse, 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._SetTriggeringResponse.deepCopy(), nil
}

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

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

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

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

// CreateSetTriggeringResponseBuilder creates a SetTriggeringResponseBuilder
func (b *_SetTriggeringResponse) CreateSetTriggeringResponseBuilder() SetTriggeringResponseBuilder {
	if b == nil {
		return NewSetTriggeringResponseBuilder()
	}
	return &_SetTriggeringResponseBuilder{_SetTriggeringResponse: b.deepCopy()}
}

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

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

func (m *_SetTriggeringResponse) GetExtensionId() int32 {
	return int32(778)
}

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

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

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

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

func (m *_SetTriggeringResponse) GetAddResults() []StatusCode {
	return m.AddResults
}

func (m *_SetTriggeringResponse) GetAddDiagnosticInfos() []DiagnosticInfo {
	return m.AddDiagnosticInfos
}

func (m *_SetTriggeringResponse) GetRemoveResults() []StatusCode {
	return m.RemoveResults
}

func (m *_SetTriggeringResponse) GetRemoveDiagnosticInfos() []DiagnosticInfo {
	return m.RemoveDiagnosticInfos
}

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

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

func (m *_SetTriggeringResponse) GetTypeName() string {
	return "SetTriggeringResponse"
}

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

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

	// Implicit Field (noOfAddResults)
	lengthInBits += 32

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

	// Implicit Field (noOfAddDiagnosticInfos)
	lengthInBits += 32

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

	// Implicit Field (noOfRemoveResults)
	lengthInBits += 32

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

	// Implicit Field (noOfRemoveDiagnosticInfos)
	lengthInBits += 32

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

	return lengthInBits
}

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

func (m *_SetTriggeringResponse) parse(ctx context.Context, readBuffer utils.ReadBuffer, parent *_ExtensionObjectDefinition, extensionId int32) (__setTriggeringResponse SetTriggeringResponse, err error) {
	m.ExtensionObjectDefinitionContract = parent
	parent._SubType = m
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("SetTriggeringResponse"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for SetTriggeringResponse")
	}
	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

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

	addResults, err := ReadCountArrayField[StatusCode](ctx, "addResults", ReadComplex[StatusCode](StatusCodeParseWithBuffer, readBuffer), uint64(noOfAddResults))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'addResults' field"))
	}
	m.AddResults = addResults

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

	addDiagnosticInfos, err := ReadCountArrayField[DiagnosticInfo](ctx, "addDiagnosticInfos", ReadComplex[DiagnosticInfo](DiagnosticInfoParseWithBuffer, readBuffer), uint64(noOfAddDiagnosticInfos))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'addDiagnosticInfos' field"))
	}
	m.AddDiagnosticInfos = addDiagnosticInfos

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

	removeResults, err := ReadCountArrayField[StatusCode](ctx, "removeResults", ReadComplex[StatusCode](StatusCodeParseWithBuffer, readBuffer), uint64(noOfRemoveResults))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'removeResults' field"))
	}
	m.RemoveResults = removeResults

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

	removeDiagnosticInfos, err := ReadCountArrayField[DiagnosticInfo](ctx, "removeDiagnosticInfos", ReadComplex[DiagnosticInfo](DiagnosticInfoParseWithBuffer, readBuffer), uint64(noOfRemoveDiagnosticInfos))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'removeDiagnosticInfos' field"))
	}
	m.RemoveDiagnosticInfos = removeDiagnosticInfos

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

	return m, nil
}

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

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

		if err := WriteComplexTypeArrayField(ctx, "addResults", m.GetAddResults(), writeBuffer); err != nil {
			return errors.Wrap(err, "Error serializing 'addResults' field")
		}
		noOfAddDiagnosticInfos := int32(utils.InlineIf(bool((m.GetAddDiagnosticInfos()) == (nil)), func() any { return int32(-(int32(1))) }, func() any { return int32(int32(len(m.GetAddDiagnosticInfos()))) }).(int32))
		if err := WriteImplicitField(ctx, "noOfAddDiagnosticInfos", noOfAddDiagnosticInfos, WriteSignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'noOfAddDiagnosticInfos' field")
		}

		if err := WriteComplexTypeArrayField(ctx, "addDiagnosticInfos", m.GetAddDiagnosticInfos(), writeBuffer); err != nil {
			return errors.Wrap(err, "Error serializing 'addDiagnosticInfos' field")
		}
		noOfRemoveResults := int32(utils.InlineIf(bool((m.GetRemoveResults()) == (nil)), func() any { return int32(-(int32(1))) }, func() any { return int32(int32(len(m.GetRemoveResults()))) }).(int32))
		if err := WriteImplicitField(ctx, "noOfRemoveResults", noOfRemoveResults, WriteSignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'noOfRemoveResults' field")
		}

		if err := WriteComplexTypeArrayField(ctx, "removeResults", m.GetRemoveResults(), writeBuffer); err != nil {
			return errors.Wrap(err, "Error serializing 'removeResults' field")
		}
		noOfRemoveDiagnosticInfos := int32(utils.InlineIf(bool((m.GetRemoveDiagnosticInfos()) == (nil)), func() any { return int32(-(int32(1))) }, func() any { return int32(int32(len(m.GetRemoveDiagnosticInfos()))) }).(int32))
		if err := WriteImplicitField(ctx, "noOfRemoveDiagnosticInfos", noOfRemoveDiagnosticInfos, WriteSignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'noOfRemoveDiagnosticInfos' field")
		}

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

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

func (m *_SetTriggeringResponse) IsSetTriggeringResponse() {}

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

func (m *_SetTriggeringResponse) deepCopy() *_SetTriggeringResponse {
	if m == nil {
		return nil
	}
	_SetTriggeringResponseCopy := &_SetTriggeringResponse{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[ResponseHeader](m.ResponseHeader),
		utils.DeepCopySlice[StatusCode, StatusCode](m.AddResults),
		utils.DeepCopySlice[DiagnosticInfo, DiagnosticInfo](m.AddDiagnosticInfos),
		utils.DeepCopySlice[StatusCode, StatusCode](m.RemoveResults),
		utils.DeepCopySlice[DiagnosticInfo, DiagnosticInfo](m.RemoveDiagnosticInfos),
	}
	_SetTriggeringResponseCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _SetTriggeringResponseCopy
}

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