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

// ContentFilterElement is the corresponding interface of ContentFilterElement
type ContentFilterElement interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetFilterOperator returns FilterOperator (property field)
	GetFilterOperator() FilterOperator
	// GetFilterOperands returns FilterOperands (property field)
	GetFilterOperands() []ExtensionObject
	// IsContentFilterElement is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsContentFilterElement()
	// CreateBuilder creates a ContentFilterElementBuilder
	CreateContentFilterElementBuilder() ContentFilterElementBuilder
}

// _ContentFilterElement is the data-structure of this message
type _ContentFilterElement struct {
	ExtensionObjectDefinitionContract
	FilterOperator FilterOperator
	FilterOperands []ExtensionObject
}

var _ ContentFilterElement = (*_ContentFilterElement)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_ContentFilterElement)(nil)

// NewContentFilterElement factory function for _ContentFilterElement
func NewContentFilterElement(filterOperator FilterOperator, filterOperands []ExtensionObject) *_ContentFilterElement {
	_result := &_ContentFilterElement{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		FilterOperator:                    filterOperator,
		FilterOperands:                    filterOperands,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// ContentFilterElementBuilder is a builder for ContentFilterElement
type ContentFilterElementBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(filterOperator FilterOperator, filterOperands []ExtensionObject) ContentFilterElementBuilder
	// WithFilterOperator adds FilterOperator (property field)
	WithFilterOperator(FilterOperator) ContentFilterElementBuilder
	// WithFilterOperands adds FilterOperands (property field)
	WithFilterOperands(...ExtensionObject) ContentFilterElementBuilder
	// 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 ContentFilterElement or returns an error if something is wrong
	Build() (ContentFilterElement, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() ContentFilterElement
}

// NewContentFilterElementBuilder() creates a ContentFilterElementBuilder
func NewContentFilterElementBuilder() ContentFilterElementBuilder {
	return &_ContentFilterElementBuilder{_ContentFilterElement: new(_ContentFilterElement)}
}

type _ContentFilterElementBuilder struct {
	*_ContentFilterElement

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (ContentFilterElementBuilder) = (*_ContentFilterElementBuilder)(nil)

func (b *_ContentFilterElementBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._ContentFilterElement
}

func (b *_ContentFilterElementBuilder) WithMandatoryFields(filterOperator FilterOperator, filterOperands []ExtensionObject) ContentFilterElementBuilder {
	return b.WithFilterOperator(filterOperator).WithFilterOperands(filterOperands...)
}

func (b *_ContentFilterElementBuilder) WithFilterOperator(filterOperator FilterOperator) ContentFilterElementBuilder {
	b.FilterOperator = filterOperator
	return b
}

func (b *_ContentFilterElementBuilder) WithFilterOperands(filterOperands ...ExtensionObject) ContentFilterElementBuilder {
	b.FilterOperands = filterOperands
	return b
}

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

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

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

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

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

// CreateContentFilterElementBuilder creates a ContentFilterElementBuilder
func (b *_ContentFilterElement) CreateContentFilterElementBuilder() ContentFilterElementBuilder {
	if b == nil {
		return NewContentFilterElementBuilder()
	}
	return &_ContentFilterElementBuilder{_ContentFilterElement: b.deepCopy()}
}

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

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

func (m *_ContentFilterElement) GetExtensionId() int32 {
	return int32(585)
}

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

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

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

func (m *_ContentFilterElement) GetFilterOperator() FilterOperator {
	return m.FilterOperator
}

func (m *_ContentFilterElement) GetFilterOperands() []ExtensionObject {
	return m.FilterOperands
}

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

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

func (m *_ContentFilterElement) GetTypeName() string {
	return "ContentFilterElement"
}

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

	// Simple field (filterOperator)
	lengthInBits += 32

	// Implicit Field (noOfFilterOperands)
	lengthInBits += 32

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

	return lengthInBits
}

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

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

	filterOperator, err := ReadEnumField[FilterOperator](ctx, "filterOperator", "FilterOperator", ReadEnum(FilterOperatorByValue, ReadUnsignedInt(readBuffer, uint8(32))))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'filterOperator' field"))
	}
	m.FilterOperator = filterOperator

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

	filterOperands, err := ReadCountArrayField[ExtensionObject](ctx, "filterOperands", ReadComplex[ExtensionObject](ExtensionObjectParseWithBufferProducer[ExtensionObject]((bool)(bool(true))), readBuffer), uint64(noOfFilterOperands))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'filterOperands' field"))
	}
	m.FilterOperands = filterOperands

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

	return m, nil
}

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

		if err := WriteSimpleEnumField[FilterOperator](ctx, "filterOperator", "FilterOperator", m.GetFilterOperator(), WriteEnum[FilterOperator, uint32](FilterOperator.GetValue, FilterOperator.PLC4XEnumName, WriteUnsignedInt(writeBuffer, 32))); err != nil {
			return errors.Wrap(err, "Error serializing 'filterOperator' field")
		}
		noOfFilterOperands := int32(utils.InlineIf(bool((m.GetFilterOperands()) == (nil)), func() any { return int32(-(int32(1))) }, func() any { return int32(int32(len(m.GetFilterOperands()))) }).(int32))
		if err := WriteImplicitField(ctx, "noOfFilterOperands", noOfFilterOperands, WriteSignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'noOfFilterOperands' field")
		}

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

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

func (m *_ContentFilterElement) IsContentFilterElement() {}

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

func (m *_ContentFilterElement) deepCopy() *_ContentFilterElement {
	if m == nil {
		return nil
	}
	_ContentFilterElementCopy := &_ContentFilterElement{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		m.FilterOperator,
		utils.DeepCopySlice[ExtensionObject, ExtensionObject](m.FilterOperands),
	}
	_ContentFilterElementCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _ContentFilterElementCopy
}

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