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

// ResponseHeader is the corresponding interface of ResponseHeader
type ResponseHeader interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetTimestamp returns Timestamp (property field)
	GetTimestamp() int64
	// GetRequestHandle returns RequestHandle (property field)
	GetRequestHandle() uint32
	// GetServiceResult returns ServiceResult (property field)
	GetServiceResult() StatusCode
	// GetServiceDiagnostics returns ServiceDiagnostics (property field)
	GetServiceDiagnostics() DiagnosticInfo
	// GetStringTable returns StringTable (property field)
	GetStringTable() []PascalString
	// GetAdditionalHeader returns AdditionalHeader (property field)
	GetAdditionalHeader() ExtensionObject
	// IsResponseHeader is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsResponseHeader()
	// CreateBuilder creates a ResponseHeaderBuilder
	CreateResponseHeaderBuilder() ResponseHeaderBuilder
}

// _ResponseHeader is the data-structure of this message
type _ResponseHeader struct {
	ExtensionObjectDefinitionContract
	Timestamp          int64
	RequestHandle      uint32
	ServiceResult      StatusCode
	ServiceDiagnostics DiagnosticInfo
	StringTable        []PascalString
	AdditionalHeader   ExtensionObject
}

var _ ResponseHeader = (*_ResponseHeader)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_ResponseHeader)(nil)

// NewResponseHeader factory function for _ResponseHeader
func NewResponseHeader(timestamp int64, requestHandle uint32, serviceResult StatusCode, serviceDiagnostics DiagnosticInfo, stringTable []PascalString, additionalHeader ExtensionObject) *_ResponseHeader {
	if serviceResult == nil {
		panic("serviceResult of type StatusCode for ResponseHeader must not be nil")
	}
	if serviceDiagnostics == nil {
		panic("serviceDiagnostics of type DiagnosticInfo for ResponseHeader must not be nil")
	}
	if additionalHeader == nil {
		panic("additionalHeader of type ExtensionObject for ResponseHeader must not be nil")
	}
	_result := &_ResponseHeader{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		Timestamp:                         timestamp,
		RequestHandle:                     requestHandle,
		ServiceResult:                     serviceResult,
		ServiceDiagnostics:                serviceDiagnostics,
		StringTable:                       stringTable,
		AdditionalHeader:                  additionalHeader,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// ResponseHeaderBuilder is a builder for ResponseHeader
type ResponseHeaderBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(timestamp int64, requestHandle uint32, serviceResult StatusCode, serviceDiagnostics DiagnosticInfo, stringTable []PascalString, additionalHeader ExtensionObject) ResponseHeaderBuilder
	// WithTimestamp adds Timestamp (property field)
	WithTimestamp(int64) ResponseHeaderBuilder
	// WithRequestHandle adds RequestHandle (property field)
	WithRequestHandle(uint32) ResponseHeaderBuilder
	// WithServiceResult adds ServiceResult (property field)
	WithServiceResult(StatusCode) ResponseHeaderBuilder
	// WithServiceResultBuilder adds ServiceResult (property field) which is build by the builder
	WithServiceResultBuilder(func(StatusCodeBuilder) StatusCodeBuilder) ResponseHeaderBuilder
	// WithServiceDiagnostics adds ServiceDiagnostics (property field)
	WithServiceDiagnostics(DiagnosticInfo) ResponseHeaderBuilder
	// WithServiceDiagnosticsBuilder adds ServiceDiagnostics (property field) which is build by the builder
	WithServiceDiagnosticsBuilder(func(DiagnosticInfoBuilder) DiagnosticInfoBuilder) ResponseHeaderBuilder
	// WithStringTable adds StringTable (property field)
	WithStringTable(...PascalString) ResponseHeaderBuilder
	// WithAdditionalHeader adds AdditionalHeader (property field)
	WithAdditionalHeader(ExtensionObject) ResponseHeaderBuilder
	// WithAdditionalHeaderBuilder adds AdditionalHeader (property field) which is build by the builder
	WithAdditionalHeaderBuilder(func(ExtensionObjectBuilder) ExtensionObjectBuilder) ResponseHeaderBuilder
	// 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 ResponseHeader or returns an error if something is wrong
	Build() (ResponseHeader, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() ResponseHeader
}

// NewResponseHeaderBuilder() creates a ResponseHeaderBuilder
func NewResponseHeaderBuilder() ResponseHeaderBuilder {
	return &_ResponseHeaderBuilder{_ResponseHeader: new(_ResponseHeader)}
}

type _ResponseHeaderBuilder struct {
	*_ResponseHeader

	parentBuilder *_ExtensionObjectDefinitionBuilder

	err *utils.MultiError
}

var _ (ResponseHeaderBuilder) = (*_ResponseHeaderBuilder)(nil)

func (b *_ResponseHeaderBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._ResponseHeader
}

func (b *_ResponseHeaderBuilder) WithMandatoryFields(timestamp int64, requestHandle uint32, serviceResult StatusCode, serviceDiagnostics DiagnosticInfo, stringTable []PascalString, additionalHeader ExtensionObject) ResponseHeaderBuilder {
	return b.WithTimestamp(timestamp).WithRequestHandle(requestHandle).WithServiceResult(serviceResult).WithServiceDiagnostics(serviceDiagnostics).WithStringTable(stringTable...).WithAdditionalHeader(additionalHeader)
}

func (b *_ResponseHeaderBuilder) WithTimestamp(timestamp int64) ResponseHeaderBuilder {
	b.Timestamp = timestamp
	return b
}

func (b *_ResponseHeaderBuilder) WithRequestHandle(requestHandle uint32) ResponseHeaderBuilder {
	b.RequestHandle = requestHandle
	return b
}

func (b *_ResponseHeaderBuilder) WithServiceResult(serviceResult StatusCode) ResponseHeaderBuilder {
	b.ServiceResult = serviceResult
	return b
}

func (b *_ResponseHeaderBuilder) WithServiceResultBuilder(builderSupplier func(StatusCodeBuilder) StatusCodeBuilder) ResponseHeaderBuilder {
	builder := builderSupplier(b.ServiceResult.CreateStatusCodeBuilder())
	var err error
	b.ServiceResult, 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, "StatusCodeBuilder failed"))
	}
	return b
}

func (b *_ResponseHeaderBuilder) WithServiceDiagnostics(serviceDiagnostics DiagnosticInfo) ResponseHeaderBuilder {
	b.ServiceDiagnostics = serviceDiagnostics
	return b
}

func (b *_ResponseHeaderBuilder) WithServiceDiagnosticsBuilder(builderSupplier func(DiagnosticInfoBuilder) DiagnosticInfoBuilder) ResponseHeaderBuilder {
	builder := builderSupplier(b.ServiceDiagnostics.CreateDiagnosticInfoBuilder())
	var err error
	b.ServiceDiagnostics, 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, "DiagnosticInfoBuilder failed"))
	}
	return b
}

func (b *_ResponseHeaderBuilder) WithStringTable(stringTable ...PascalString) ResponseHeaderBuilder {
	b.StringTable = stringTable
	return b
}

func (b *_ResponseHeaderBuilder) WithAdditionalHeader(additionalHeader ExtensionObject) ResponseHeaderBuilder {
	b.AdditionalHeader = additionalHeader
	return b
}

func (b *_ResponseHeaderBuilder) WithAdditionalHeaderBuilder(builderSupplier func(ExtensionObjectBuilder) ExtensionObjectBuilder) ResponseHeaderBuilder {
	builder := builderSupplier(b.AdditionalHeader.CreateExtensionObjectBuilder())
	var err error
	b.AdditionalHeader, 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, "ExtensionObjectBuilder failed"))
	}
	return b
}

func (b *_ResponseHeaderBuilder) Build() (ResponseHeader, error) {
	if b.ServiceResult == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'serviceResult' not set"))
	}
	if b.ServiceDiagnostics == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'serviceDiagnostics' not set"))
	}
	if b.AdditionalHeader == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'additionalHeader' not set"))
	}
	if b.err != nil {
		return nil, errors.Wrap(b.err, "error occurred during build")
	}
	return b._ResponseHeader.deepCopy(), nil
}

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

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

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

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

// CreateResponseHeaderBuilder creates a ResponseHeaderBuilder
func (b *_ResponseHeader) CreateResponseHeaderBuilder() ResponseHeaderBuilder {
	if b == nil {
		return NewResponseHeaderBuilder()
	}
	return &_ResponseHeaderBuilder{_ResponseHeader: b.deepCopy()}
}

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

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

func (m *_ResponseHeader) GetExtensionId() int32 {
	return int32(394)
}

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

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

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

func (m *_ResponseHeader) GetTimestamp() int64 {
	return m.Timestamp
}

func (m *_ResponseHeader) GetRequestHandle() uint32 {
	return m.RequestHandle
}

func (m *_ResponseHeader) GetServiceResult() StatusCode {
	return m.ServiceResult
}

func (m *_ResponseHeader) GetServiceDiagnostics() DiagnosticInfo {
	return m.ServiceDiagnostics
}

func (m *_ResponseHeader) GetStringTable() []PascalString {
	return m.StringTable
}

func (m *_ResponseHeader) GetAdditionalHeader() ExtensionObject {
	return m.AdditionalHeader
}

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

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

func (m *_ResponseHeader) GetTypeName() string {
	return "ResponseHeader"
}

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

	// Simple field (timestamp)
	lengthInBits += 64

	// Simple field (requestHandle)
	lengthInBits += 32

	// Simple field (serviceResult)
	lengthInBits += m.ServiceResult.GetLengthInBits(ctx)

	// Simple field (serviceDiagnostics)
	lengthInBits += m.ServiceDiagnostics.GetLengthInBits(ctx)

	// Implicit Field (noOfStringTable)
	lengthInBits += 32

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

	// Simple field (additionalHeader)
	lengthInBits += m.AdditionalHeader.GetLengthInBits(ctx)

	return lengthInBits
}

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

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

	timestamp, err := ReadSimpleField(ctx, "timestamp", ReadSignedLong(readBuffer, uint8(64)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'timestamp' field"))
	}
	m.Timestamp = timestamp

	requestHandle, err := ReadSimpleField(ctx, "requestHandle", ReadUnsignedInt(readBuffer, uint8(32)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'requestHandle' field"))
	}
	m.RequestHandle = requestHandle

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

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

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

	stringTable, err := ReadCountArrayField[PascalString](ctx, "stringTable", ReadComplex[PascalString](PascalStringParseWithBuffer, readBuffer), uint64(noOfStringTable))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'stringTable' field"))
	}
	m.StringTable = stringTable

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

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

	return m, nil
}

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

		if err := WriteSimpleField[int64](ctx, "timestamp", m.GetTimestamp(), WriteSignedLong(writeBuffer, 64)); err != nil {
			return errors.Wrap(err, "Error serializing 'timestamp' field")
		}

		if err := WriteSimpleField[uint32](ctx, "requestHandle", m.GetRequestHandle(), WriteUnsignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'requestHandle' field")
		}

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

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

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

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

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

func (m *_ResponseHeader) IsResponseHeader() {}

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

func (m *_ResponseHeader) deepCopy() *_ResponseHeader {
	if m == nil {
		return nil
	}
	_ResponseHeaderCopy := &_ResponseHeader{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		m.Timestamp,
		m.RequestHandle,
		utils.DeepCopy[StatusCode](m.ServiceResult),
		utils.DeepCopy[DiagnosticInfo](m.ServiceDiagnostics),
		utils.DeepCopySlice[PascalString, PascalString](m.StringTable),
		utils.DeepCopy[ExtensionObject](m.AdditionalHeader),
	}
	_ResponseHeaderCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _ResponseHeaderCopy
}

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