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

// OpenSecureChannelResponse is the corresponding interface of OpenSecureChannelResponse
type OpenSecureChannelResponse interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetResponseHeader returns ResponseHeader (property field)
	GetResponseHeader() ResponseHeader
	// GetServerProtocolVersion returns ServerProtocolVersion (property field)
	GetServerProtocolVersion() uint32
	// GetSecurityToken returns SecurityToken (property field)
	GetSecurityToken() ChannelSecurityToken
	// GetServerNonce returns ServerNonce (property field)
	GetServerNonce() PascalByteString
	// IsOpenSecureChannelResponse is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsOpenSecureChannelResponse()
	// CreateBuilder creates a OpenSecureChannelResponseBuilder
	CreateOpenSecureChannelResponseBuilder() OpenSecureChannelResponseBuilder
}

// _OpenSecureChannelResponse is the data-structure of this message
type _OpenSecureChannelResponse struct {
	ExtensionObjectDefinitionContract
	ResponseHeader        ResponseHeader
	ServerProtocolVersion uint32
	SecurityToken         ChannelSecurityToken
	ServerNonce           PascalByteString
}

var _ OpenSecureChannelResponse = (*_OpenSecureChannelResponse)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_OpenSecureChannelResponse)(nil)

// NewOpenSecureChannelResponse factory function for _OpenSecureChannelResponse
func NewOpenSecureChannelResponse(responseHeader ResponseHeader, serverProtocolVersion uint32, securityToken ChannelSecurityToken, serverNonce PascalByteString) *_OpenSecureChannelResponse {
	if responseHeader == nil {
		panic("responseHeader of type ResponseHeader for OpenSecureChannelResponse must not be nil")
	}
	if securityToken == nil {
		panic("securityToken of type ChannelSecurityToken for OpenSecureChannelResponse must not be nil")
	}
	if serverNonce == nil {
		panic("serverNonce of type PascalByteString for OpenSecureChannelResponse must not be nil")
	}
	_result := &_OpenSecureChannelResponse{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		ResponseHeader:                    responseHeader,
		ServerProtocolVersion:             serverProtocolVersion,
		SecurityToken:                     securityToken,
		ServerNonce:                       serverNonce,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// OpenSecureChannelResponseBuilder is a builder for OpenSecureChannelResponse
type OpenSecureChannelResponseBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(responseHeader ResponseHeader, serverProtocolVersion uint32, securityToken ChannelSecurityToken, serverNonce PascalByteString) OpenSecureChannelResponseBuilder
	// WithResponseHeader adds ResponseHeader (property field)
	WithResponseHeader(ResponseHeader) OpenSecureChannelResponseBuilder
	// WithResponseHeaderBuilder adds ResponseHeader (property field) which is build by the builder
	WithResponseHeaderBuilder(func(ResponseHeaderBuilder) ResponseHeaderBuilder) OpenSecureChannelResponseBuilder
	// WithServerProtocolVersion adds ServerProtocolVersion (property field)
	WithServerProtocolVersion(uint32) OpenSecureChannelResponseBuilder
	// WithSecurityToken adds SecurityToken (property field)
	WithSecurityToken(ChannelSecurityToken) OpenSecureChannelResponseBuilder
	// WithSecurityTokenBuilder adds SecurityToken (property field) which is build by the builder
	WithSecurityTokenBuilder(func(ChannelSecurityTokenBuilder) ChannelSecurityTokenBuilder) OpenSecureChannelResponseBuilder
	// WithServerNonce adds ServerNonce (property field)
	WithServerNonce(PascalByteString) OpenSecureChannelResponseBuilder
	// WithServerNonceBuilder adds ServerNonce (property field) which is build by the builder
	WithServerNonceBuilder(func(PascalByteStringBuilder) PascalByteStringBuilder) OpenSecureChannelResponseBuilder
	// 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 OpenSecureChannelResponse or returns an error if something is wrong
	Build() (OpenSecureChannelResponse, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() OpenSecureChannelResponse
}

// NewOpenSecureChannelResponseBuilder() creates a OpenSecureChannelResponseBuilder
func NewOpenSecureChannelResponseBuilder() OpenSecureChannelResponseBuilder {
	return &_OpenSecureChannelResponseBuilder{_OpenSecureChannelResponse: new(_OpenSecureChannelResponse)}
}

type _OpenSecureChannelResponseBuilder struct {
	*_OpenSecureChannelResponse

	parentBuilder *_ExtensionObjectDefinitionBuilder

	err *utils.MultiError
}

var _ (OpenSecureChannelResponseBuilder) = (*_OpenSecureChannelResponseBuilder)(nil)

func (b *_OpenSecureChannelResponseBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._OpenSecureChannelResponse
}

func (b *_OpenSecureChannelResponseBuilder) WithMandatoryFields(responseHeader ResponseHeader, serverProtocolVersion uint32, securityToken ChannelSecurityToken, serverNonce PascalByteString) OpenSecureChannelResponseBuilder {
	return b.WithResponseHeader(responseHeader).WithServerProtocolVersion(serverProtocolVersion).WithSecurityToken(securityToken).WithServerNonce(serverNonce)
}

func (b *_OpenSecureChannelResponseBuilder) WithResponseHeader(responseHeader ResponseHeader) OpenSecureChannelResponseBuilder {
	b.ResponseHeader = responseHeader
	return b
}

func (b *_OpenSecureChannelResponseBuilder) WithResponseHeaderBuilder(builderSupplier func(ResponseHeaderBuilder) ResponseHeaderBuilder) OpenSecureChannelResponseBuilder {
	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 *_OpenSecureChannelResponseBuilder) WithServerProtocolVersion(serverProtocolVersion uint32) OpenSecureChannelResponseBuilder {
	b.ServerProtocolVersion = serverProtocolVersion
	return b
}

func (b *_OpenSecureChannelResponseBuilder) WithSecurityToken(securityToken ChannelSecurityToken) OpenSecureChannelResponseBuilder {
	b.SecurityToken = securityToken
	return b
}

func (b *_OpenSecureChannelResponseBuilder) WithSecurityTokenBuilder(builderSupplier func(ChannelSecurityTokenBuilder) ChannelSecurityTokenBuilder) OpenSecureChannelResponseBuilder {
	builder := builderSupplier(b.SecurityToken.CreateChannelSecurityTokenBuilder())
	var err error
	b.SecurityToken, 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, "ChannelSecurityTokenBuilder failed"))
	}
	return b
}

func (b *_OpenSecureChannelResponseBuilder) WithServerNonce(serverNonce PascalByteString) OpenSecureChannelResponseBuilder {
	b.ServerNonce = serverNonce
	return b
}

func (b *_OpenSecureChannelResponseBuilder) WithServerNonceBuilder(builderSupplier func(PascalByteStringBuilder) PascalByteStringBuilder) OpenSecureChannelResponseBuilder {
	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 *_OpenSecureChannelResponseBuilder) Build() (OpenSecureChannelResponse, 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.SecurityToken == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'securityToken' 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._OpenSecureChannelResponse.deepCopy(), nil
}

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

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

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

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

// CreateOpenSecureChannelResponseBuilder creates a OpenSecureChannelResponseBuilder
func (b *_OpenSecureChannelResponse) CreateOpenSecureChannelResponseBuilder() OpenSecureChannelResponseBuilder {
	if b == nil {
		return NewOpenSecureChannelResponseBuilder()
	}
	return &_OpenSecureChannelResponseBuilder{_OpenSecureChannelResponse: b.deepCopy()}
}

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

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

func (m *_OpenSecureChannelResponse) GetExtensionId() int32 {
	return int32(449)
}

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

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

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

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

func (m *_OpenSecureChannelResponse) GetServerProtocolVersion() uint32 {
	return m.ServerProtocolVersion
}

func (m *_OpenSecureChannelResponse) GetSecurityToken() ChannelSecurityToken {
	return m.SecurityToken
}

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

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

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

func (m *_OpenSecureChannelResponse) GetTypeName() string {
	return "OpenSecureChannelResponse"
}

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

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

	// Simple field (serverProtocolVersion)
	lengthInBits += 32

	// Simple field (securityToken)
	lengthInBits += m.SecurityToken.GetLengthInBits(ctx)

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

	return lengthInBits
}

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

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

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

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

	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

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

	return m, nil
}

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

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

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

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

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

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

func (m *_OpenSecureChannelResponse) IsOpenSecureChannelResponse() {}

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

func (m *_OpenSecureChannelResponse) deepCopy() *_OpenSecureChannelResponse {
	if m == nil {
		return nil
	}
	_OpenSecureChannelResponseCopy := &_OpenSecureChannelResponse{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[ResponseHeader](m.ResponseHeader),
		m.ServerProtocolVersion,
		utils.DeepCopy[ChannelSecurityToken](m.SecurityToken),
		utils.DeepCopy[PascalByteString](m.ServerNonce),
	}
	_OpenSecureChannelResponseCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _OpenSecureChannelResponseCopy
}

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