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

// ParsingResult is the corresponding interface of ParsingResult
type ParsingResult interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetStatusCode returns StatusCode (property field)
	GetStatusCode() StatusCode
	// GetDataStatusCodes returns DataStatusCodes (property field)
	GetDataStatusCodes() []StatusCode
	// GetDataDiagnosticInfos returns DataDiagnosticInfos (property field)
	GetDataDiagnosticInfos() []DiagnosticInfo
	// IsParsingResult is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsParsingResult()
	// CreateBuilder creates a ParsingResultBuilder
	CreateParsingResultBuilder() ParsingResultBuilder
}

// _ParsingResult is the data-structure of this message
type _ParsingResult struct {
	ExtensionObjectDefinitionContract
	StatusCode          StatusCode
	DataStatusCodes     []StatusCode
	DataDiagnosticInfos []DiagnosticInfo
}

var _ ParsingResult = (*_ParsingResult)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_ParsingResult)(nil)

// NewParsingResult factory function for _ParsingResult
func NewParsingResult(statusCode StatusCode, dataStatusCodes []StatusCode, dataDiagnosticInfos []DiagnosticInfo) *_ParsingResult {
	if statusCode == nil {
		panic("statusCode of type StatusCode for ParsingResult must not be nil")
	}
	_result := &_ParsingResult{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		StatusCode:                        statusCode,
		DataStatusCodes:                   dataStatusCodes,
		DataDiagnosticInfos:               dataDiagnosticInfos,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// ParsingResultBuilder is a builder for ParsingResult
type ParsingResultBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(statusCode StatusCode, dataStatusCodes []StatusCode, dataDiagnosticInfos []DiagnosticInfo) ParsingResultBuilder
	// WithStatusCode adds StatusCode (property field)
	WithStatusCode(StatusCode) ParsingResultBuilder
	// WithStatusCodeBuilder adds StatusCode (property field) which is build by the builder
	WithStatusCodeBuilder(func(StatusCodeBuilder) StatusCodeBuilder) ParsingResultBuilder
	// WithDataStatusCodes adds DataStatusCodes (property field)
	WithDataStatusCodes(...StatusCode) ParsingResultBuilder
	// WithDataDiagnosticInfos adds DataDiagnosticInfos (property field)
	WithDataDiagnosticInfos(...DiagnosticInfo) ParsingResultBuilder
	// 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 ParsingResult or returns an error if something is wrong
	Build() (ParsingResult, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() ParsingResult
}

// NewParsingResultBuilder() creates a ParsingResultBuilder
func NewParsingResultBuilder() ParsingResultBuilder {
	return &_ParsingResultBuilder{_ParsingResult: new(_ParsingResult)}
}

type _ParsingResultBuilder struct {
	*_ParsingResult

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (ParsingResultBuilder) = (*_ParsingResultBuilder)(nil)

func (b *_ParsingResultBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._ParsingResult
}

func (b *_ParsingResultBuilder) WithMandatoryFields(statusCode StatusCode, dataStatusCodes []StatusCode, dataDiagnosticInfos []DiagnosticInfo) ParsingResultBuilder {
	return b.WithStatusCode(statusCode).WithDataStatusCodes(dataStatusCodes...).WithDataDiagnosticInfos(dataDiagnosticInfos...)
}

func (b *_ParsingResultBuilder) WithStatusCode(statusCode StatusCode) ParsingResultBuilder {
	b.StatusCode = statusCode
	return b
}

func (b *_ParsingResultBuilder) WithStatusCodeBuilder(builderSupplier func(StatusCodeBuilder) StatusCodeBuilder) ParsingResultBuilder {
	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 *_ParsingResultBuilder) WithDataStatusCodes(dataStatusCodes ...StatusCode) ParsingResultBuilder {
	b.DataStatusCodes = dataStatusCodes
	return b
}

func (b *_ParsingResultBuilder) WithDataDiagnosticInfos(dataDiagnosticInfos ...DiagnosticInfo) ParsingResultBuilder {
	b.DataDiagnosticInfos = dataDiagnosticInfos
	return b
}

func (b *_ParsingResultBuilder) Build() (ParsingResult, 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._ParsingResult.deepCopy(), nil
}

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

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

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

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

// CreateParsingResultBuilder creates a ParsingResultBuilder
func (b *_ParsingResult) CreateParsingResultBuilder() ParsingResultBuilder {
	if b == nil {
		return NewParsingResultBuilder()
	}
	return &_ParsingResultBuilder{_ParsingResult: b.deepCopy()}
}

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

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

func (m *_ParsingResult) GetExtensionId() int32 {
	return int32(612)
}

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

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

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

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

func (m *_ParsingResult) GetDataStatusCodes() []StatusCode {
	return m.DataStatusCodes
}

func (m *_ParsingResult) GetDataDiagnosticInfos() []DiagnosticInfo {
	return m.DataDiagnosticInfos
}

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

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

func (m *_ParsingResult) GetTypeName() string {
	return "ParsingResult"
}

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

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

	// Implicit Field (noOfDataStatusCodes)
	lengthInBits += 32

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

	// Implicit Field (noOfDataDiagnosticInfos)
	lengthInBits += 32

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

	return lengthInBits
}

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

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

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

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

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

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

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

	return m, nil
}

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

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

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

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

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

func (m *_ParsingResult) IsParsingResult() {}

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

func (m *_ParsingResult) deepCopy() *_ParsingResult {
	if m == nil {
		return nil
	}
	_ParsingResultCopy := &_ParsingResult{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[StatusCode](m.StatusCode),
		utils.DeepCopySlice[StatusCode, StatusCode](m.DataStatusCodes),
		utils.DeepCopySlice[DiagnosticInfo, DiagnosticInfo](m.DataDiagnosticInfos),
	}
	_ParsingResultCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _ParsingResultCopy
}

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