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

// ContentFilterResult is the corresponding interface of ContentFilterResult
type ContentFilterResult interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetElementResults returns ElementResults (property field)
	GetElementResults() []ContentFilterElementResult
	// GetElementDiagnosticInfos returns ElementDiagnosticInfos (property field)
	GetElementDiagnosticInfos() []DiagnosticInfo
	// IsContentFilterResult is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsContentFilterResult()
	// CreateBuilder creates a ContentFilterResultBuilder
	CreateContentFilterResultBuilder() ContentFilterResultBuilder
}

// _ContentFilterResult is the data-structure of this message
type _ContentFilterResult struct {
	ExtensionObjectDefinitionContract
	ElementResults         []ContentFilterElementResult
	ElementDiagnosticInfos []DiagnosticInfo
}

var _ ContentFilterResult = (*_ContentFilterResult)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_ContentFilterResult)(nil)

// NewContentFilterResult factory function for _ContentFilterResult
func NewContentFilterResult(elementResults []ContentFilterElementResult, elementDiagnosticInfos []DiagnosticInfo) *_ContentFilterResult {
	_result := &_ContentFilterResult{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		ElementResults:                    elementResults,
		ElementDiagnosticInfos:            elementDiagnosticInfos,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// ContentFilterResultBuilder is a builder for ContentFilterResult
type ContentFilterResultBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(elementResults []ContentFilterElementResult, elementDiagnosticInfos []DiagnosticInfo) ContentFilterResultBuilder
	// WithElementResults adds ElementResults (property field)
	WithElementResults(...ContentFilterElementResult) ContentFilterResultBuilder
	// WithElementDiagnosticInfos adds ElementDiagnosticInfos (property field)
	WithElementDiagnosticInfos(...DiagnosticInfo) ContentFilterResultBuilder
	// 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 ContentFilterResult or returns an error if something is wrong
	Build() (ContentFilterResult, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() ContentFilterResult
}

// NewContentFilterResultBuilder() creates a ContentFilterResultBuilder
func NewContentFilterResultBuilder() ContentFilterResultBuilder {
	return &_ContentFilterResultBuilder{_ContentFilterResult: new(_ContentFilterResult)}
}

type _ContentFilterResultBuilder struct {
	*_ContentFilterResult

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (ContentFilterResultBuilder) = (*_ContentFilterResultBuilder)(nil)

func (b *_ContentFilterResultBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._ContentFilterResult
}

func (b *_ContentFilterResultBuilder) WithMandatoryFields(elementResults []ContentFilterElementResult, elementDiagnosticInfos []DiagnosticInfo) ContentFilterResultBuilder {
	return b.WithElementResults(elementResults...).WithElementDiagnosticInfos(elementDiagnosticInfos...)
}

func (b *_ContentFilterResultBuilder) WithElementResults(elementResults ...ContentFilterElementResult) ContentFilterResultBuilder {
	b.ElementResults = elementResults
	return b
}

func (b *_ContentFilterResultBuilder) WithElementDiagnosticInfos(elementDiagnosticInfos ...DiagnosticInfo) ContentFilterResultBuilder {
	b.ElementDiagnosticInfos = elementDiagnosticInfos
	return b
}

func (b *_ContentFilterResultBuilder) Build() (ContentFilterResult, error) {
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._ContentFilterResult.deepCopy(), nil
}

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

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

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

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

// CreateContentFilterResultBuilder creates a ContentFilterResultBuilder
func (b *_ContentFilterResult) CreateContentFilterResultBuilder() ContentFilterResultBuilder {
	if b == nil {
		return NewContentFilterResultBuilder()
	}
	return &_ContentFilterResultBuilder{_ContentFilterResult: b.deepCopy()}
}

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

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

func (m *_ContentFilterResult) GetExtensionId() int32 {
	return int32(609)
}

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

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

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

func (m *_ContentFilterResult) GetElementResults() []ContentFilterElementResult {
	return m.ElementResults
}

func (m *_ContentFilterResult) GetElementDiagnosticInfos() []DiagnosticInfo {
	return m.ElementDiagnosticInfos
}

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

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

func (m *_ContentFilterResult) GetTypeName() string {
	return "ContentFilterResult"
}

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

	// Implicit Field (noOfElementResults)
	lengthInBits += 32

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

	// Implicit Field (noOfElementDiagnosticInfos)
	lengthInBits += 32

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

	return lengthInBits
}

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

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

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

	elementResults, err := ReadCountArrayField[ContentFilterElementResult](ctx, "elementResults", ReadComplex[ContentFilterElementResult](ExtensionObjectDefinitionParseWithBufferProducer[ContentFilterElementResult]((int32)(int32(606))), readBuffer), uint64(noOfElementResults))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'elementResults' field"))
	}
	m.ElementResults = elementResults

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

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

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

	return m, nil
}

func (m *_ContentFilterResult) 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 *_ContentFilterResult) SerializeWithWriteBuffer(ctx context.Context, writeBuffer utils.WriteBuffer) error {
	positionAware := writeBuffer
	_ = positionAware
	log := zerolog.Ctx(ctx)
	_ = log
	ser := func() error {
		if pushErr := writeBuffer.PushContext("ContentFilterResult"); pushErr != nil {
			return errors.Wrap(pushErr, "Error pushing for ContentFilterResult")
		}
		noOfElementResults := int32(utils.InlineIf(bool((m.GetElementResults()) == (nil)), func() any { return int32(-(int32(1))) }, func() any { return int32(int32(len(m.GetElementResults()))) }).(int32))
		if err := WriteImplicitField(ctx, "noOfElementResults", noOfElementResults, WriteSignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'noOfElementResults' field")
		}

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

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

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

func (m *_ContentFilterResult) IsContentFilterResult() {}

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

func (m *_ContentFilterResult) deepCopy() *_ContentFilterResult {
	if m == nil {
		return nil
	}
	_ContentFilterResultCopy := &_ContentFilterResult{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopySlice[ContentFilterElementResult, ContentFilterElementResult](m.ElementResults),
		utils.DeepCopySlice[DiagnosticInfo, DiagnosticInfo](m.ElementDiagnosticInfos),
	}
	_ContentFilterResultCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _ContentFilterResultCopy
}

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