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

// NLMSetMasterKey is the corresponding interface of NLMSetMasterKey
type NLMSetMasterKey interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	NLM
	// GetKey returns Key (property field)
	GetKey() NLMUpdateKeyUpdateKeyEntry
	// IsNLMSetMasterKey is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsNLMSetMasterKey()
	// CreateBuilder creates a NLMSetMasterKeyBuilder
	CreateNLMSetMasterKeyBuilder() NLMSetMasterKeyBuilder
}

// _NLMSetMasterKey is the data-structure of this message
type _NLMSetMasterKey struct {
	NLMContract
	Key NLMUpdateKeyUpdateKeyEntry
}

var _ NLMSetMasterKey = (*_NLMSetMasterKey)(nil)
var _ NLMRequirements = (*_NLMSetMasterKey)(nil)

// NewNLMSetMasterKey factory function for _NLMSetMasterKey
func NewNLMSetMasterKey(key NLMUpdateKeyUpdateKeyEntry, apduLength uint16) *_NLMSetMasterKey {
	if key == nil {
		panic("key of type NLMUpdateKeyUpdateKeyEntry for NLMSetMasterKey must not be nil")
	}
	_result := &_NLMSetMasterKey{
		NLMContract: NewNLM(apduLength),
		Key:         key,
	}
	_result.NLMContract.(*_NLM)._SubType = _result
	return _result
}

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

// NLMSetMasterKeyBuilder is a builder for NLMSetMasterKey
type NLMSetMasterKeyBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(key NLMUpdateKeyUpdateKeyEntry) NLMSetMasterKeyBuilder
	// WithKey adds Key (property field)
	WithKey(NLMUpdateKeyUpdateKeyEntry) NLMSetMasterKeyBuilder
	// WithKeyBuilder adds Key (property field) which is build by the builder
	WithKeyBuilder(func(NLMUpdateKeyUpdateKeyEntryBuilder) NLMUpdateKeyUpdateKeyEntryBuilder) NLMSetMasterKeyBuilder
	// 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 NLMSetMasterKey or returns an error if something is wrong
	Build() (NLMSetMasterKey, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() NLMSetMasterKey
}

// NewNLMSetMasterKeyBuilder() creates a NLMSetMasterKeyBuilder
func NewNLMSetMasterKeyBuilder() NLMSetMasterKeyBuilder {
	return &_NLMSetMasterKeyBuilder{_NLMSetMasterKey: new(_NLMSetMasterKey)}
}

type _NLMSetMasterKeyBuilder struct {
	*_NLMSetMasterKey

	parentBuilder *_NLMBuilder

	err *utils.MultiError
}

var _ (NLMSetMasterKeyBuilder) = (*_NLMSetMasterKeyBuilder)(nil)

func (b *_NLMSetMasterKeyBuilder) setParent(contract NLMContract) {
	b.NLMContract = contract
	contract.(*_NLM)._SubType = b._NLMSetMasterKey
}

func (b *_NLMSetMasterKeyBuilder) WithMandatoryFields(key NLMUpdateKeyUpdateKeyEntry) NLMSetMasterKeyBuilder {
	return b.WithKey(key)
}

func (b *_NLMSetMasterKeyBuilder) WithKey(key NLMUpdateKeyUpdateKeyEntry) NLMSetMasterKeyBuilder {
	b.Key = key
	return b
}

func (b *_NLMSetMasterKeyBuilder) WithKeyBuilder(builderSupplier func(NLMUpdateKeyUpdateKeyEntryBuilder) NLMUpdateKeyUpdateKeyEntryBuilder) NLMSetMasterKeyBuilder {
	builder := builderSupplier(b.Key.CreateNLMUpdateKeyUpdateKeyEntryBuilder())
	var err error
	b.Key, 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, "NLMUpdateKeyUpdateKeyEntryBuilder failed"))
	}
	return b
}

func (b *_NLMSetMasterKeyBuilder) Build() (NLMSetMasterKey, error) {
	if b.Key == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'key' not set"))
	}
	if b.err != nil {
		return nil, errors.Wrap(b.err, "error occurred during build")
	}
	return b._NLMSetMasterKey.deepCopy(), nil
}

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

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

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

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

// CreateNLMSetMasterKeyBuilder creates a NLMSetMasterKeyBuilder
func (b *_NLMSetMasterKey) CreateNLMSetMasterKeyBuilder() NLMSetMasterKeyBuilder {
	if b == nil {
		return NewNLMSetMasterKeyBuilder()
	}
	return &_NLMSetMasterKeyBuilder{_NLMSetMasterKey: b.deepCopy()}
}

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

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

func (m *_NLMSetMasterKey) GetMessageType() uint8 {
	return 0x11
}

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

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

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

func (m *_NLMSetMasterKey) GetKey() NLMUpdateKeyUpdateKeyEntry {
	return m.Key
}

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

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

func (m *_NLMSetMasterKey) GetTypeName() string {
	return "NLMSetMasterKey"
}

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

	// Simple field (key)
	lengthInBits += m.Key.GetLengthInBits(ctx)

	return lengthInBits
}

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

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

	key, err := ReadSimpleField[NLMUpdateKeyUpdateKeyEntry](ctx, "key", ReadComplex[NLMUpdateKeyUpdateKeyEntry](NLMUpdateKeyUpdateKeyEntryParseWithBuffer, readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'key' field"))
	}
	m.Key = key

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

	return m, nil
}

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

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

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

func (m *_NLMSetMasterKey) IsNLMSetMasterKey() {}

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

func (m *_NLMSetMasterKey) deepCopy() *_NLMSetMasterKey {
	if m == nil {
		return nil
	}
	_NLMSetMasterKeyCopy := &_NLMSetMasterKey{
		m.NLMContract.(*_NLM).deepCopy(),
		utils.DeepCopy[NLMUpdateKeyUpdateKeyEntry](m.Key),
	}
	_NLMSetMasterKeyCopy.NLMContract.(*_NLM)._SubType = m
	return _NLMSetMasterKeyCopy
}

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