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

// CallMethodResult is the corresponding interface of CallMethodResult
type CallMethodResult interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetStatusCode returns StatusCode (property field)
	GetStatusCode() StatusCode
	// GetInputArgumentResults returns InputArgumentResults (property field)
	GetInputArgumentResults() []StatusCode
	// GetInputArgumentDiagnosticInfos returns InputArgumentDiagnosticInfos (property field)
	GetInputArgumentDiagnosticInfos() []DiagnosticInfo
	// GetOutputArguments returns OutputArguments (property field)
	GetOutputArguments() []Variant
	// IsCallMethodResult is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsCallMethodResult()
	// CreateBuilder creates a CallMethodResultBuilder
	CreateCallMethodResultBuilder() CallMethodResultBuilder
}

// _CallMethodResult is the data-structure of this message
type _CallMethodResult struct {
	ExtensionObjectDefinitionContract
	StatusCode                   StatusCode
	InputArgumentResults         []StatusCode
	InputArgumentDiagnosticInfos []DiagnosticInfo
	OutputArguments              []Variant
}

var _ CallMethodResult = (*_CallMethodResult)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_CallMethodResult)(nil)

// NewCallMethodResult factory function for _CallMethodResult
func NewCallMethodResult(statusCode StatusCode, inputArgumentResults []StatusCode, inputArgumentDiagnosticInfos []DiagnosticInfo, outputArguments []Variant) *_CallMethodResult {
	if statusCode == nil {
		panic("statusCode of type StatusCode for CallMethodResult must not be nil")
	}
	_result := &_CallMethodResult{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		StatusCode:                        statusCode,
		InputArgumentResults:              inputArgumentResults,
		InputArgumentDiagnosticInfos:      inputArgumentDiagnosticInfos,
		OutputArguments:                   outputArguments,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// CallMethodResultBuilder is a builder for CallMethodResult
type CallMethodResultBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(statusCode StatusCode, inputArgumentResults []StatusCode, inputArgumentDiagnosticInfos []DiagnosticInfo, outputArguments []Variant) CallMethodResultBuilder
	// WithStatusCode adds StatusCode (property field)
	WithStatusCode(StatusCode) CallMethodResultBuilder
	// WithStatusCodeBuilder adds StatusCode (property field) which is build by the builder
	WithStatusCodeBuilder(func(StatusCodeBuilder) StatusCodeBuilder) CallMethodResultBuilder
	// WithInputArgumentResults adds InputArgumentResults (property field)
	WithInputArgumentResults(...StatusCode) CallMethodResultBuilder
	// WithInputArgumentDiagnosticInfos adds InputArgumentDiagnosticInfos (property field)
	WithInputArgumentDiagnosticInfos(...DiagnosticInfo) CallMethodResultBuilder
	// WithOutputArguments adds OutputArguments (property field)
	WithOutputArguments(...Variant) CallMethodResultBuilder
	// 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 CallMethodResult or returns an error if something is wrong
	Build() (CallMethodResult, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() CallMethodResult
}

// NewCallMethodResultBuilder() creates a CallMethodResultBuilder
func NewCallMethodResultBuilder() CallMethodResultBuilder {
	return &_CallMethodResultBuilder{_CallMethodResult: new(_CallMethodResult)}
}

type _CallMethodResultBuilder struct {
	*_CallMethodResult

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (CallMethodResultBuilder) = (*_CallMethodResultBuilder)(nil)

func (b *_CallMethodResultBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._CallMethodResult
}

func (b *_CallMethodResultBuilder) WithMandatoryFields(statusCode StatusCode, inputArgumentResults []StatusCode, inputArgumentDiagnosticInfos []DiagnosticInfo, outputArguments []Variant) CallMethodResultBuilder {
	return b.WithStatusCode(statusCode).WithInputArgumentResults(inputArgumentResults...).WithInputArgumentDiagnosticInfos(inputArgumentDiagnosticInfos...).WithOutputArguments(outputArguments...)
}

func (b *_CallMethodResultBuilder) WithStatusCode(statusCode StatusCode) CallMethodResultBuilder {
	b.StatusCode = statusCode
	return b
}

func (b *_CallMethodResultBuilder) WithStatusCodeBuilder(builderSupplier func(StatusCodeBuilder) StatusCodeBuilder) CallMethodResultBuilder {
	builder := builderSupplier(b.StatusCode.CreateStatusCodeBuilder())
	var err error
	b.StatusCode, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "StatusCodeBuilder failed"))
	}
	return b
}

func (b *_CallMethodResultBuilder) WithInputArgumentResults(inputArgumentResults ...StatusCode) CallMethodResultBuilder {
	b.InputArgumentResults = inputArgumentResults
	return b
}

func (b *_CallMethodResultBuilder) WithInputArgumentDiagnosticInfos(inputArgumentDiagnosticInfos ...DiagnosticInfo) CallMethodResultBuilder {
	b.InputArgumentDiagnosticInfos = inputArgumentDiagnosticInfos
	return b
}

func (b *_CallMethodResultBuilder) WithOutputArguments(outputArguments ...Variant) CallMethodResultBuilder {
	b.OutputArguments = outputArguments
	return b
}

func (b *_CallMethodResultBuilder) Build() (CallMethodResult, error) {
	if b.StatusCode == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'statusCode' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._CallMethodResult.deepCopy(), nil
}

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

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

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

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

// CreateCallMethodResultBuilder creates a CallMethodResultBuilder
func (b *_CallMethodResult) CreateCallMethodResultBuilder() CallMethodResultBuilder {
	if b == nil {
		return NewCallMethodResultBuilder()
	}
	return &_CallMethodResultBuilder{_CallMethodResult: b.deepCopy()}
}

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

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

func (m *_CallMethodResult) GetExtensionId() int32 {
	return int32(709)
}

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

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

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

func (m *_CallMethodResult) GetStatusCode() StatusCode {
	return m.StatusCode
}

func (m *_CallMethodResult) GetInputArgumentResults() []StatusCode {
	return m.InputArgumentResults
}

func (m *_CallMethodResult) GetInputArgumentDiagnosticInfos() []DiagnosticInfo {
	return m.InputArgumentDiagnosticInfos
}

func (m *_CallMethodResult) GetOutputArguments() []Variant {
	return m.OutputArguments
}

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

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

func (m *_CallMethodResult) GetTypeName() string {
	return "CallMethodResult"
}

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

	// Simple field (statusCode)
	lengthInBits += m.StatusCode.GetLengthInBits(ctx)

	// Implicit Field (noOfInputArgumentResults)
	lengthInBits += 32

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

	// Implicit Field (noOfInputArgumentDiagnosticInfos)
	lengthInBits += 32

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

	// Implicit Field (noOfOutputArguments)
	lengthInBits += 32

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

	return lengthInBits
}

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

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

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

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

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

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

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

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

	outputArguments, err := ReadCountArrayField[Variant](ctx, "outputArguments", ReadComplex[Variant](VariantParseWithBuffer, readBuffer), uint64(noOfOutputArguments))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'outputArguments' field"))
	}
	m.OutputArguments = outputArguments

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

	return m, nil
}

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

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

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

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

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

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

func (m *_CallMethodResult) IsCallMethodResult() {}

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

func (m *_CallMethodResult) deepCopy() *_CallMethodResult {
	if m == nil {
		return nil
	}
	_CallMethodResultCopy := &_CallMethodResult{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[StatusCode](m.StatusCode),
		utils.DeepCopySlice[StatusCode, StatusCode](m.InputArgumentResults),
		utils.DeepCopySlice[DiagnosticInfo, DiagnosticInfo](m.InputArgumentDiagnosticInfos),
		utils.DeepCopySlice[Variant, Variant](m.OutputArguments),
	}
	_CallMethodResultCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _CallMethodResultCopy
}

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