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

// ActivateSessionResponse is the corresponding interface of ActivateSessionResponse
type ActivateSessionResponse interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetResponseHeader returns ResponseHeader (property field)
	GetResponseHeader() ResponseHeader
	// GetServerNonce returns ServerNonce (property field)
	GetServerNonce() PascalByteString
	// GetResults returns Results (property field)
	GetResults() []StatusCode
	// GetDiagnosticInfos returns DiagnosticInfos (property field)
	GetDiagnosticInfos() []DiagnosticInfo
	// IsActivateSessionResponse is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsActivateSessionResponse()
	// CreateBuilder creates a ActivateSessionResponseBuilder
	CreateActivateSessionResponseBuilder() ActivateSessionResponseBuilder
}

// _ActivateSessionResponse is the data-structure of this message
type _ActivateSessionResponse struct {
	ExtensionObjectDefinitionContract
	ResponseHeader  ResponseHeader
	ServerNonce     PascalByteString
	Results         []StatusCode
	DiagnosticInfos []DiagnosticInfo
}

var _ ActivateSessionResponse = (*_ActivateSessionResponse)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_ActivateSessionResponse)(nil)

// NewActivateSessionResponse factory function for _ActivateSessionResponse
func NewActivateSessionResponse(responseHeader ResponseHeader, serverNonce PascalByteString, results []StatusCode, diagnosticInfos []DiagnosticInfo) *_ActivateSessionResponse {
	if responseHeader == nil {
		panic("responseHeader of type ResponseHeader for ActivateSessionResponse must not be nil")
	}
	if serverNonce == nil {
		panic("serverNonce of type PascalByteString for ActivateSessionResponse must not be nil")
	}
	_result := &_ActivateSessionResponse{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		ResponseHeader:                    responseHeader,
		ServerNonce:                       serverNonce,
		Results:                           results,
		DiagnosticInfos:                   diagnosticInfos,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// ActivateSessionResponseBuilder is a builder for ActivateSessionResponse
type ActivateSessionResponseBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(responseHeader ResponseHeader, serverNonce PascalByteString, results []StatusCode, diagnosticInfos []DiagnosticInfo) ActivateSessionResponseBuilder
	// WithResponseHeader adds ResponseHeader (property field)
	WithResponseHeader(ResponseHeader) ActivateSessionResponseBuilder
	// WithResponseHeaderBuilder adds ResponseHeader (property field) which is build by the builder
	WithResponseHeaderBuilder(func(ResponseHeaderBuilder) ResponseHeaderBuilder) ActivateSessionResponseBuilder
	// WithServerNonce adds ServerNonce (property field)
	WithServerNonce(PascalByteString) ActivateSessionResponseBuilder
	// WithServerNonceBuilder adds ServerNonce (property field) which is build by the builder
	WithServerNonceBuilder(func(PascalByteStringBuilder) PascalByteStringBuilder) ActivateSessionResponseBuilder
	// WithResults adds Results (property field)
	WithResults(...StatusCode) ActivateSessionResponseBuilder
	// WithDiagnosticInfos adds DiagnosticInfos (property field)
	WithDiagnosticInfos(...DiagnosticInfo) ActivateSessionResponseBuilder
	// 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 ActivateSessionResponse or returns an error if something is wrong
	Build() (ActivateSessionResponse, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() ActivateSessionResponse
}

// NewActivateSessionResponseBuilder() creates a ActivateSessionResponseBuilder
func NewActivateSessionResponseBuilder() ActivateSessionResponseBuilder {
	return &_ActivateSessionResponseBuilder{_ActivateSessionResponse: new(_ActivateSessionResponse)}
}

type _ActivateSessionResponseBuilder struct {
	*_ActivateSessionResponse

	parentBuilder *_ExtensionObjectDefinitionBuilder

	err *utils.MultiError
}

var _ (ActivateSessionResponseBuilder) = (*_ActivateSessionResponseBuilder)(nil)

func (b *_ActivateSessionResponseBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._ActivateSessionResponse
}

func (b *_ActivateSessionResponseBuilder) WithMandatoryFields(responseHeader ResponseHeader, serverNonce PascalByteString, results []StatusCode, diagnosticInfos []DiagnosticInfo) ActivateSessionResponseBuilder {
	return b.WithResponseHeader(responseHeader).WithServerNonce(serverNonce).WithResults(results...).WithDiagnosticInfos(diagnosticInfos...)
}

func (b *_ActivateSessionResponseBuilder) WithResponseHeader(responseHeader ResponseHeader) ActivateSessionResponseBuilder {
	b.ResponseHeader = responseHeader
	return b
}

func (b *_ActivateSessionResponseBuilder) WithResponseHeaderBuilder(builderSupplier func(ResponseHeaderBuilder) ResponseHeaderBuilder) ActivateSessionResponseBuilder {
	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 *_ActivateSessionResponseBuilder) WithServerNonce(serverNonce PascalByteString) ActivateSessionResponseBuilder {
	b.ServerNonce = serverNonce
	return b
}

func (b *_ActivateSessionResponseBuilder) WithServerNonceBuilder(builderSupplier func(PascalByteStringBuilder) PascalByteStringBuilder) ActivateSessionResponseBuilder {
	builder := builderSupplier(b.ServerNonce.CreatePascalByteStringBuilder())
	var err error
	b.ServerNonce, 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, "PascalByteStringBuilder failed"))
	}
	return b
}

func (b *_ActivateSessionResponseBuilder) WithResults(results ...StatusCode) ActivateSessionResponseBuilder {
	b.Results = results
	return b
}

func (b *_ActivateSessionResponseBuilder) WithDiagnosticInfos(diagnosticInfos ...DiagnosticInfo) ActivateSessionResponseBuilder {
	b.DiagnosticInfos = diagnosticInfos
	return b
}

func (b *_ActivateSessionResponseBuilder) Build() (ActivateSessionResponse, 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.ServerNonce == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'serverNonce' not set"))
	}
	if b.err != nil {
		return nil, errors.Wrap(b.err, "error occurred during build")
	}
	return b._ActivateSessionResponse.deepCopy(), nil
}

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

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

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

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

// CreateActivateSessionResponseBuilder creates a ActivateSessionResponseBuilder
func (b *_ActivateSessionResponse) CreateActivateSessionResponseBuilder() ActivateSessionResponseBuilder {
	if b == nil {
		return NewActivateSessionResponseBuilder()
	}
	return &_ActivateSessionResponseBuilder{_ActivateSessionResponse: b.deepCopy()}
}

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

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

func (m *_ActivateSessionResponse) GetExtensionId() int32 {
	return int32(470)
}

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

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

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

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

func (m *_ActivateSessionResponse) GetServerNonce() PascalByteString {
	return m.ServerNonce
}

func (m *_ActivateSessionResponse) GetResults() []StatusCode {
	return m.Results
}

func (m *_ActivateSessionResponse) GetDiagnosticInfos() []DiagnosticInfo {
	return m.DiagnosticInfos
}

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

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

func (m *_ActivateSessionResponse) GetTypeName() string {
	return "ActivateSessionResponse"
}

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

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

	// Simple field (serverNonce)
	lengthInBits += m.ServerNonce.GetLengthInBits(ctx)

	// Implicit Field (noOfResults)
	lengthInBits += 32

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

	// Implicit Field (noOfDiagnosticInfos)
	lengthInBits += 32

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

	return lengthInBits
}

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

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

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

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

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

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

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

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

	return m, nil
}

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

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

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

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

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

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

func (m *_ActivateSessionResponse) IsActivateSessionResponse() {}

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

func (m *_ActivateSessionResponse) deepCopy() *_ActivateSessionResponse {
	if m == nil {
		return nil
	}
	_ActivateSessionResponseCopy := &_ActivateSessionResponse{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[ResponseHeader](m.ResponseHeader),
		utils.DeepCopy[PascalByteString](m.ServerNonce),
		utils.DeepCopySlice[StatusCode, StatusCode](m.Results),
		utils.DeepCopySlice[DiagnosticInfo, DiagnosticInfo](m.DiagnosticInfos),
	}
	_ActivateSessionResponseCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _ActivateSessionResponseCopy
}

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