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

// WritePropertyMultipleError is the corresponding interface of WritePropertyMultipleError
type WritePropertyMultipleError interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	BACnetError
	// GetErrorType returns ErrorType (property field)
	GetErrorType() ErrorEnclosed
	// GetFirstFailedWriteAttempt returns FirstFailedWriteAttempt (property field)
	GetFirstFailedWriteAttempt() BACnetObjectPropertyReferenceEnclosed
	// IsWritePropertyMultipleError is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsWritePropertyMultipleError()
	// CreateBuilder creates a WritePropertyMultipleErrorBuilder
	CreateWritePropertyMultipleErrorBuilder() WritePropertyMultipleErrorBuilder
}

// _WritePropertyMultipleError is the data-structure of this message
type _WritePropertyMultipleError struct {
	BACnetErrorContract
	ErrorType               ErrorEnclosed
	FirstFailedWriteAttempt BACnetObjectPropertyReferenceEnclosed
}

var _ WritePropertyMultipleError = (*_WritePropertyMultipleError)(nil)
var _ BACnetErrorRequirements = (*_WritePropertyMultipleError)(nil)

// NewWritePropertyMultipleError factory function for _WritePropertyMultipleError
func NewWritePropertyMultipleError(errorType ErrorEnclosed, firstFailedWriteAttempt BACnetObjectPropertyReferenceEnclosed) *_WritePropertyMultipleError {
	if errorType == nil {
		panic("errorType of type ErrorEnclosed for WritePropertyMultipleError must not be nil")
	}
	if firstFailedWriteAttempt == nil {
		panic("firstFailedWriteAttempt of type BACnetObjectPropertyReferenceEnclosed for WritePropertyMultipleError must not be nil")
	}
	_result := &_WritePropertyMultipleError{
		BACnetErrorContract:     NewBACnetError(),
		ErrorType:               errorType,
		FirstFailedWriteAttempt: firstFailedWriteAttempt,
	}
	_result.BACnetErrorContract.(*_BACnetError)._SubType = _result
	return _result
}

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

// WritePropertyMultipleErrorBuilder is a builder for WritePropertyMultipleError
type WritePropertyMultipleErrorBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(errorType ErrorEnclosed, firstFailedWriteAttempt BACnetObjectPropertyReferenceEnclosed) WritePropertyMultipleErrorBuilder
	// WithErrorType adds ErrorType (property field)
	WithErrorType(ErrorEnclosed) WritePropertyMultipleErrorBuilder
	// WithErrorTypeBuilder adds ErrorType (property field) which is build by the builder
	WithErrorTypeBuilder(func(ErrorEnclosedBuilder) ErrorEnclosedBuilder) WritePropertyMultipleErrorBuilder
	// WithFirstFailedWriteAttempt adds FirstFailedWriteAttempt (property field)
	WithFirstFailedWriteAttempt(BACnetObjectPropertyReferenceEnclosed) WritePropertyMultipleErrorBuilder
	// WithFirstFailedWriteAttemptBuilder adds FirstFailedWriteAttempt (property field) which is build by the builder
	WithFirstFailedWriteAttemptBuilder(func(BACnetObjectPropertyReferenceEnclosedBuilder) BACnetObjectPropertyReferenceEnclosedBuilder) WritePropertyMultipleErrorBuilder
	// Done is used to finish work on this child and return (or create one if none) to the parent builder
	Done() BACnetErrorBuilder
	// Build builds the WritePropertyMultipleError or returns an error if something is wrong
	Build() (WritePropertyMultipleError, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() WritePropertyMultipleError
}

// NewWritePropertyMultipleErrorBuilder() creates a WritePropertyMultipleErrorBuilder
func NewWritePropertyMultipleErrorBuilder() WritePropertyMultipleErrorBuilder {
	return &_WritePropertyMultipleErrorBuilder{_WritePropertyMultipleError: new(_WritePropertyMultipleError)}
}

type _WritePropertyMultipleErrorBuilder struct {
	*_WritePropertyMultipleError

	parentBuilder *_BACnetErrorBuilder

	collectedErr []error
}

var _ (WritePropertyMultipleErrorBuilder) = (*_WritePropertyMultipleErrorBuilder)(nil)

func (b *_WritePropertyMultipleErrorBuilder) setParent(contract BACnetErrorContract) {
	b.BACnetErrorContract = contract
	contract.(*_BACnetError)._SubType = b._WritePropertyMultipleError
}

func (b *_WritePropertyMultipleErrorBuilder) WithMandatoryFields(errorType ErrorEnclosed, firstFailedWriteAttempt BACnetObjectPropertyReferenceEnclosed) WritePropertyMultipleErrorBuilder {
	return b.WithErrorType(errorType).WithFirstFailedWriteAttempt(firstFailedWriteAttempt)
}

func (b *_WritePropertyMultipleErrorBuilder) WithErrorType(errorType ErrorEnclosed) WritePropertyMultipleErrorBuilder {
	b.ErrorType = errorType
	return b
}

func (b *_WritePropertyMultipleErrorBuilder) WithErrorTypeBuilder(builderSupplier func(ErrorEnclosedBuilder) ErrorEnclosedBuilder) WritePropertyMultipleErrorBuilder {
	builder := builderSupplier(b.ErrorType.CreateErrorEnclosedBuilder())
	var err error
	b.ErrorType, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "ErrorEnclosedBuilder failed"))
	}
	return b
}

func (b *_WritePropertyMultipleErrorBuilder) WithFirstFailedWriteAttempt(firstFailedWriteAttempt BACnetObjectPropertyReferenceEnclosed) WritePropertyMultipleErrorBuilder {
	b.FirstFailedWriteAttempt = firstFailedWriteAttempt
	return b
}

func (b *_WritePropertyMultipleErrorBuilder) WithFirstFailedWriteAttemptBuilder(builderSupplier func(BACnetObjectPropertyReferenceEnclosedBuilder) BACnetObjectPropertyReferenceEnclosedBuilder) WritePropertyMultipleErrorBuilder {
	builder := builderSupplier(b.FirstFailedWriteAttempt.CreateBACnetObjectPropertyReferenceEnclosedBuilder())
	var err error
	b.FirstFailedWriteAttempt, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "BACnetObjectPropertyReferenceEnclosedBuilder failed"))
	}
	return b
}

func (b *_WritePropertyMultipleErrorBuilder) Build() (WritePropertyMultipleError, error) {
	if b.ErrorType == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'errorType' not set"))
	}
	if b.FirstFailedWriteAttempt == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'firstFailedWriteAttempt' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._WritePropertyMultipleError.deepCopy(), nil
}

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

func (b *_WritePropertyMultipleErrorBuilder) Done() BACnetErrorBuilder {
	if b.parentBuilder == nil {
		b.parentBuilder = NewBACnetErrorBuilder().(*_BACnetErrorBuilder)
	}
	return b.parentBuilder
}

func (b *_WritePropertyMultipleErrorBuilder) buildForBACnetError() (BACnetError, error) {
	return b.Build()
}

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

// CreateWritePropertyMultipleErrorBuilder creates a WritePropertyMultipleErrorBuilder
func (b *_WritePropertyMultipleError) CreateWritePropertyMultipleErrorBuilder() WritePropertyMultipleErrorBuilder {
	if b == nil {
		return NewWritePropertyMultipleErrorBuilder()
	}
	return &_WritePropertyMultipleErrorBuilder{_WritePropertyMultipleError: b.deepCopy()}
}

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

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

func (m *_WritePropertyMultipleError) GetErrorChoice() BACnetConfirmedServiceChoice {
	return BACnetConfirmedServiceChoice_WRITE_PROPERTY_MULTIPLE
}

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

func (m *_WritePropertyMultipleError) GetParent() BACnetErrorContract {
	return m.BACnetErrorContract
}

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

func (m *_WritePropertyMultipleError) GetErrorType() ErrorEnclosed {
	return m.ErrorType
}

func (m *_WritePropertyMultipleError) GetFirstFailedWriteAttempt() BACnetObjectPropertyReferenceEnclosed {
	return m.FirstFailedWriteAttempt
}

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

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

func (m *_WritePropertyMultipleError) GetTypeName() string {
	return "WritePropertyMultipleError"
}

func (m *_WritePropertyMultipleError) GetLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(m.BACnetErrorContract.(*_BACnetError).getLengthInBits(ctx))

	// Simple field (errorType)
	lengthInBits += m.ErrorType.GetLengthInBits(ctx)

	// Simple field (firstFailedWriteAttempt)
	lengthInBits += m.FirstFailedWriteAttempt.GetLengthInBits(ctx)

	return lengthInBits
}

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

func (m *_WritePropertyMultipleError) parse(ctx context.Context, readBuffer utils.ReadBuffer, parent *_BACnetError, errorChoice BACnetConfirmedServiceChoice) (__writePropertyMultipleError WritePropertyMultipleError, err error) {
	m.BACnetErrorContract = parent
	parent._SubType = m
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("WritePropertyMultipleError"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for WritePropertyMultipleError")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

	errorType, err := ReadSimpleField[ErrorEnclosed](ctx, "errorType", ReadComplex[ErrorEnclosed](ErrorEnclosedParseWithBufferProducer((uint8)(uint8(0))), readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'errorType' field"))
	}
	m.ErrorType = errorType

	firstFailedWriteAttempt, err := ReadSimpleField[BACnetObjectPropertyReferenceEnclosed](ctx, "firstFailedWriteAttempt", ReadComplex[BACnetObjectPropertyReferenceEnclosed](BACnetObjectPropertyReferenceEnclosedParseWithBufferProducer((uint8)(uint8(1))), readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'firstFailedWriteAttempt' field"))
	}
	m.FirstFailedWriteAttempt = firstFailedWriteAttempt

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

	return m, nil
}

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

		if err := WriteSimpleField[ErrorEnclosed](ctx, "errorType", m.GetErrorType(), WriteComplex[ErrorEnclosed](writeBuffer)); err != nil {
			return errors.Wrap(err, "Error serializing 'errorType' field")
		}

		if err := WriteSimpleField[BACnetObjectPropertyReferenceEnclosed](ctx, "firstFailedWriteAttempt", m.GetFirstFailedWriteAttempt(), WriteComplex[BACnetObjectPropertyReferenceEnclosed](writeBuffer)); err != nil {
			return errors.Wrap(err, "Error serializing 'firstFailedWriteAttempt' field")
		}

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

func (m *_WritePropertyMultipleError) IsWritePropertyMultipleError() {}

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

func (m *_WritePropertyMultipleError) deepCopy() *_WritePropertyMultipleError {
	if m == nil {
		return nil
	}
	_WritePropertyMultipleErrorCopy := &_WritePropertyMultipleError{
		m.BACnetErrorContract.(*_BACnetError).deepCopy(),
		utils.DeepCopy[ErrorEnclosed](m.ErrorType),
		utils.DeepCopy[BACnetObjectPropertyReferenceEnclosed](m.FirstFailedWriteAttempt),
	}
	_WritePropertyMultipleErrorCopy.BACnetErrorContract.(*_BACnetError)._SubType = m
	return _WritePropertyMultipleErrorCopy
}

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