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

// NLMSecurityPayload is the corresponding interface of NLMSecurityPayload
type NLMSecurityPayload interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	NLM
	// GetPayloadLength returns PayloadLength (property field)
	GetPayloadLength() uint16
	// GetPayload returns Payload (property field)
	GetPayload() []byte
	// IsNLMSecurityPayload is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsNLMSecurityPayload()
	// CreateBuilder creates a NLMSecurityPayloadBuilder
	CreateNLMSecurityPayloadBuilder() NLMSecurityPayloadBuilder
}

// _NLMSecurityPayload is the data-structure of this message
type _NLMSecurityPayload struct {
	NLMContract
	PayloadLength uint16
	Payload       []byte
}

var _ NLMSecurityPayload = (*_NLMSecurityPayload)(nil)
var _ NLMRequirements = (*_NLMSecurityPayload)(nil)

// NewNLMSecurityPayload factory function for _NLMSecurityPayload
func NewNLMSecurityPayload(payloadLength uint16, payload []byte, apduLength uint16) *_NLMSecurityPayload {
	_result := &_NLMSecurityPayload{
		NLMContract:   NewNLM(apduLength),
		PayloadLength: payloadLength,
		Payload:       payload,
	}
	_result.NLMContract.(*_NLM)._SubType = _result
	return _result
}

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

// NLMSecurityPayloadBuilder is a builder for NLMSecurityPayload
type NLMSecurityPayloadBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(payloadLength uint16, payload []byte) NLMSecurityPayloadBuilder
	// WithPayloadLength adds PayloadLength (property field)
	WithPayloadLength(uint16) NLMSecurityPayloadBuilder
	// WithPayload adds Payload (property field)
	WithPayload(...byte) NLMSecurityPayloadBuilder
	// Done is used to finish work on this child and return (or create one if none) to the parent builder
	Done() NLMBuilder
	// Build builds the NLMSecurityPayload or returns an error if something is wrong
	Build() (NLMSecurityPayload, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() NLMSecurityPayload
}

// NewNLMSecurityPayloadBuilder() creates a NLMSecurityPayloadBuilder
func NewNLMSecurityPayloadBuilder() NLMSecurityPayloadBuilder {
	return &_NLMSecurityPayloadBuilder{_NLMSecurityPayload: new(_NLMSecurityPayload)}
}

type _NLMSecurityPayloadBuilder struct {
	*_NLMSecurityPayload

	parentBuilder *_NLMBuilder

	err *utils.MultiError
}

var _ (NLMSecurityPayloadBuilder) = (*_NLMSecurityPayloadBuilder)(nil)

func (b *_NLMSecurityPayloadBuilder) setParent(contract NLMContract) {
	b.NLMContract = contract
	contract.(*_NLM)._SubType = b._NLMSecurityPayload
}

func (b *_NLMSecurityPayloadBuilder) WithMandatoryFields(payloadLength uint16, payload []byte) NLMSecurityPayloadBuilder {
	return b.WithPayloadLength(payloadLength).WithPayload(payload...)
}

func (b *_NLMSecurityPayloadBuilder) WithPayloadLength(payloadLength uint16) NLMSecurityPayloadBuilder {
	b.PayloadLength = payloadLength
	return b
}

func (b *_NLMSecurityPayloadBuilder) WithPayload(payload ...byte) NLMSecurityPayloadBuilder {
	b.Payload = payload
	return b
}

func (b *_NLMSecurityPayloadBuilder) Build() (NLMSecurityPayload, error) {
	if b.err != nil {
		return nil, errors.Wrap(b.err, "error occurred during build")
	}
	return b._NLMSecurityPayload.deepCopy(), nil
}

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

func (b *_NLMSecurityPayloadBuilder) Done() NLMBuilder {
	if b.parentBuilder == nil {
		b.parentBuilder = NewNLMBuilder().(*_NLMBuilder)
	}
	return b.parentBuilder
}

func (b *_NLMSecurityPayloadBuilder) buildForNLM() (NLM, error) {
	return b.Build()
}

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

// CreateNLMSecurityPayloadBuilder creates a NLMSecurityPayloadBuilder
func (b *_NLMSecurityPayload) CreateNLMSecurityPayloadBuilder() NLMSecurityPayloadBuilder {
	if b == nil {
		return NewNLMSecurityPayloadBuilder()
	}
	return &_NLMSecurityPayloadBuilder{_NLMSecurityPayload: b.deepCopy()}
}

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

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

func (m *_NLMSecurityPayload) GetMessageType() uint8 {
	return 0x0B
}

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

func (m *_NLMSecurityPayload) GetParent() NLMContract {
	return m.NLMContract
}

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

func (m *_NLMSecurityPayload) GetPayloadLength() uint16 {
	return m.PayloadLength
}

func (m *_NLMSecurityPayload) GetPayload() []byte {
	return m.Payload
}

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

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

func (m *_NLMSecurityPayload) GetTypeName() string {
	return "NLMSecurityPayload"
}

func (m *_NLMSecurityPayload) GetLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(m.NLMContract.(*_NLM).getLengthInBits(ctx))

	// Simple field (payloadLength)
	lengthInBits += 16

	// Array field
	if len(m.Payload) > 0 {
		lengthInBits += 8 * uint16(len(m.Payload))
	}

	return lengthInBits
}

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

func (m *_NLMSecurityPayload) parse(ctx context.Context, readBuffer utils.ReadBuffer, parent *_NLM, apduLength uint16) (__nLMSecurityPayload NLMSecurityPayload, err error) {
	m.NLMContract = parent
	parent._SubType = m
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("NLMSecurityPayload"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for NLMSecurityPayload")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

	payloadLength, err := ReadSimpleField(ctx, "payloadLength", ReadUnsignedShort(readBuffer, uint8(16)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'payloadLength' field"))
	}
	m.PayloadLength = payloadLength

	payload, err := readBuffer.ReadByteArray("payload", int(payloadLength))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'payload' field"))
	}
	m.Payload = payload

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

	return m, nil
}

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

		if err := WriteSimpleField[uint16](ctx, "payloadLength", m.GetPayloadLength(), WriteUnsignedShort(writeBuffer, 16)); err != nil {
			return errors.Wrap(err, "Error serializing 'payloadLength' field")
		}

		if err := WriteByteArrayField(ctx, "payload", m.GetPayload(), WriteByteArray(writeBuffer, 8)); err != nil {
			return errors.Wrap(err, "Error serializing 'payload' field")
		}

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

func (m *_NLMSecurityPayload) IsNLMSecurityPayload() {}

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

func (m *_NLMSecurityPayload) deepCopy() *_NLMSecurityPayload {
	if m == nil {
		return nil
	}
	_NLMSecurityPayloadCopy := &_NLMSecurityPayload{
		m.NLMContract.(*_NLM).deepCopy(),
		m.PayloadLength,
		utils.DeepCopySlice[byte, byte](m.Payload),
	}
	_NLMSecurityPayloadCopy.NLMContract.(*_NLM)._SubType = m
	return _NLMSecurityPayloadCopy
}

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