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

// ServiceFault is the corresponding interface of ServiceFault
type ServiceFault interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetResponseHeader returns ResponseHeader (property field)
	GetResponseHeader() ResponseHeader
	// IsServiceFault is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsServiceFault()
	// CreateBuilder creates a ServiceFaultBuilder
	CreateServiceFaultBuilder() ServiceFaultBuilder
}

// _ServiceFault is the data-structure of this message
type _ServiceFault struct {
	ExtensionObjectDefinitionContract
	ResponseHeader ResponseHeader
}

var _ ServiceFault = (*_ServiceFault)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_ServiceFault)(nil)

// NewServiceFault factory function for _ServiceFault
func NewServiceFault(responseHeader ResponseHeader) *_ServiceFault {
	if responseHeader == nil {
		panic("responseHeader of type ResponseHeader for ServiceFault must not be nil")
	}
	_result := &_ServiceFault{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		ResponseHeader:                    responseHeader,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// ServiceFaultBuilder is a builder for ServiceFault
type ServiceFaultBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(responseHeader ResponseHeader) ServiceFaultBuilder
	// WithResponseHeader adds ResponseHeader (property field)
	WithResponseHeader(ResponseHeader) ServiceFaultBuilder
	// WithResponseHeaderBuilder adds ResponseHeader (property field) which is build by the builder
	WithResponseHeaderBuilder(func(ResponseHeaderBuilder) ResponseHeaderBuilder) ServiceFaultBuilder
	// 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 ServiceFault or returns an error if something is wrong
	Build() (ServiceFault, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() ServiceFault
}

// NewServiceFaultBuilder() creates a ServiceFaultBuilder
func NewServiceFaultBuilder() ServiceFaultBuilder {
	return &_ServiceFaultBuilder{_ServiceFault: new(_ServiceFault)}
}

type _ServiceFaultBuilder struct {
	*_ServiceFault

	parentBuilder *_ExtensionObjectDefinitionBuilder

	err *utils.MultiError
}

var _ (ServiceFaultBuilder) = (*_ServiceFaultBuilder)(nil)

func (b *_ServiceFaultBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._ServiceFault
}

func (b *_ServiceFaultBuilder) WithMandatoryFields(responseHeader ResponseHeader) ServiceFaultBuilder {
	return b.WithResponseHeader(responseHeader)
}

func (b *_ServiceFaultBuilder) WithResponseHeader(responseHeader ResponseHeader) ServiceFaultBuilder {
	b.ResponseHeader = responseHeader
	return b
}

func (b *_ServiceFaultBuilder) WithResponseHeaderBuilder(builderSupplier func(ResponseHeaderBuilder) ResponseHeaderBuilder) ServiceFaultBuilder {
	builder := builderSupplier(b.ResponseHeader.CreateResponseHeaderBuilder())
	var err error
	b.ResponseHeader, err = builder.Build()
	if err != nil {
		if b.err == nil {
			b.err = &utils.MultiError{MainError: errors.New("sub builder failed")}
		}
		b.err.Append(errors.Wrap(err, "ResponseHeaderBuilder failed"))
	}
	return b
}

func (b *_ServiceFaultBuilder) Build() (ServiceFault, error) {
	if b.ResponseHeader == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'responseHeader' not set"))
	}
	if b.err != nil {
		return nil, errors.Wrap(b.err, "error occurred during build")
	}
	return b._ServiceFault.deepCopy(), nil
}

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

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

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

func (b *_ServiceFaultBuilder) DeepCopy() any {
	_copy := b.CreateServiceFaultBuilder().(*_ServiceFaultBuilder)
	if b.err != nil {
		_copy.err = b.err.DeepCopy().(*utils.MultiError)
	}
	return _copy
}

// CreateServiceFaultBuilder creates a ServiceFaultBuilder
func (b *_ServiceFault) CreateServiceFaultBuilder() ServiceFaultBuilder {
	if b == nil {
		return NewServiceFaultBuilder()
	}
	return &_ServiceFaultBuilder{_ServiceFault: b.deepCopy()}
}

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

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

func (m *_ServiceFault) GetExtensionId() int32 {
	return int32(397)
}

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

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

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

func (m *_ServiceFault) GetResponseHeader() ResponseHeader {
	return m.ResponseHeader
}

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

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

func (m *_ServiceFault) GetTypeName() string {
	return "ServiceFault"
}

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

	// Simple field (responseHeader)
	lengthInBits += m.ResponseHeader.GetLengthInBits(ctx)

	return lengthInBits
}

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

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

	responseHeader, err := ReadSimpleField[ResponseHeader](ctx, "responseHeader", ReadComplex[ResponseHeader](ExtensionObjectDefinitionParseWithBufferProducer[ResponseHeader]((int32)(int32(394))), readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'responseHeader' field"))
	}
	m.ResponseHeader = responseHeader

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

	return m, nil
}

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

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

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

func (m *_ServiceFault) IsServiceFault() {}

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

func (m *_ServiceFault) deepCopy() *_ServiceFault {
	if m == nil {
		return nil
	}
	_ServiceFaultCopy := &_ServiceFault{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[ResponseHeader](m.ResponseHeader),
	}
	_ServiceFaultCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _ServiceFaultCopy
}

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