/*
 * 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"
	stdErrors "errors"
	"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.

// BACnetPortPermission is the corresponding interface of BACnetPortPermission
type BACnetPortPermission interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	// GetPort returns Port (property field)
	GetPort() BACnetContextTagUnsignedInteger
	// GetEnable returns Enable (property field)
	GetEnable() BACnetContextTagBoolean
	// IsBACnetPortPermission is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsBACnetPortPermission()
	// CreateBuilder creates a BACnetPortPermissionBuilder
	CreateBACnetPortPermissionBuilder() BACnetPortPermissionBuilder
}

// _BACnetPortPermission is the data-structure of this message
type _BACnetPortPermission struct {
	Port   BACnetContextTagUnsignedInteger
	Enable BACnetContextTagBoolean
}

var _ BACnetPortPermission = (*_BACnetPortPermission)(nil)

// NewBACnetPortPermission factory function for _BACnetPortPermission
func NewBACnetPortPermission(port BACnetContextTagUnsignedInteger, enable BACnetContextTagBoolean) *_BACnetPortPermission {
	if port == nil {
		panic("port of type BACnetContextTagUnsignedInteger for BACnetPortPermission must not be nil")
	}
	return &_BACnetPortPermission{Port: port, Enable: enable}
}

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

// BACnetPortPermissionBuilder is a builder for BACnetPortPermission
type BACnetPortPermissionBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(port BACnetContextTagUnsignedInteger) BACnetPortPermissionBuilder
	// WithPort adds Port (property field)
	WithPort(BACnetContextTagUnsignedInteger) BACnetPortPermissionBuilder
	// WithPortBuilder adds Port (property field) which is build by the builder
	WithPortBuilder(func(BACnetContextTagUnsignedIntegerBuilder) BACnetContextTagUnsignedIntegerBuilder) BACnetPortPermissionBuilder
	// WithEnable adds Enable (property field)
	WithOptionalEnable(BACnetContextTagBoolean) BACnetPortPermissionBuilder
	// WithOptionalEnableBuilder adds Enable (property field) which is build by the builder
	WithOptionalEnableBuilder(func(BACnetContextTagBooleanBuilder) BACnetContextTagBooleanBuilder) BACnetPortPermissionBuilder
	// Build builds the BACnetPortPermission or returns an error if something is wrong
	Build() (BACnetPortPermission, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() BACnetPortPermission
}

// NewBACnetPortPermissionBuilder() creates a BACnetPortPermissionBuilder
func NewBACnetPortPermissionBuilder() BACnetPortPermissionBuilder {
	return &_BACnetPortPermissionBuilder{_BACnetPortPermission: new(_BACnetPortPermission)}
}

type _BACnetPortPermissionBuilder struct {
	*_BACnetPortPermission

	collectedErr []error
}

var _ (BACnetPortPermissionBuilder) = (*_BACnetPortPermissionBuilder)(nil)

func (b *_BACnetPortPermissionBuilder) WithMandatoryFields(port BACnetContextTagUnsignedInteger) BACnetPortPermissionBuilder {
	return b.WithPort(port)
}

func (b *_BACnetPortPermissionBuilder) WithPort(port BACnetContextTagUnsignedInteger) BACnetPortPermissionBuilder {
	b.Port = port
	return b
}

func (b *_BACnetPortPermissionBuilder) WithPortBuilder(builderSupplier func(BACnetContextTagUnsignedIntegerBuilder) BACnetContextTagUnsignedIntegerBuilder) BACnetPortPermissionBuilder {
	builder := builderSupplier(b.Port.CreateBACnetContextTagUnsignedIntegerBuilder())
	var err error
	b.Port, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "BACnetContextTagUnsignedIntegerBuilder failed"))
	}
	return b
}

func (b *_BACnetPortPermissionBuilder) WithOptionalEnable(enable BACnetContextTagBoolean) BACnetPortPermissionBuilder {
	b.Enable = enable
	return b
}

func (b *_BACnetPortPermissionBuilder) WithOptionalEnableBuilder(builderSupplier func(BACnetContextTagBooleanBuilder) BACnetContextTagBooleanBuilder) BACnetPortPermissionBuilder {
	builder := builderSupplier(b.Enable.CreateBACnetContextTagBooleanBuilder())
	var err error
	b.Enable, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "BACnetContextTagBooleanBuilder failed"))
	}
	return b
}

func (b *_BACnetPortPermissionBuilder) Build() (BACnetPortPermission, error) {
	if b.Port == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'port' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._BACnetPortPermission.deepCopy(), nil
}

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

func (b *_BACnetPortPermissionBuilder) DeepCopy() any {
	_copy := b.CreateBACnetPortPermissionBuilder().(*_BACnetPortPermissionBuilder)
	if b.collectedErr != nil {
		copy(_copy.collectedErr, b.collectedErr)
	}
	return _copy
}

// CreateBACnetPortPermissionBuilder creates a BACnetPortPermissionBuilder
func (b *_BACnetPortPermission) CreateBACnetPortPermissionBuilder() BACnetPortPermissionBuilder {
	if b == nil {
		return NewBACnetPortPermissionBuilder()
	}
	return &_BACnetPortPermissionBuilder{_BACnetPortPermission: b.deepCopy()}
}

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

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

func (m *_BACnetPortPermission) GetPort() BACnetContextTagUnsignedInteger {
	return m.Port
}

func (m *_BACnetPortPermission) GetEnable() BACnetContextTagBoolean {
	return m.Enable
}

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

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

func (m *_BACnetPortPermission) GetTypeName() string {
	return "BACnetPortPermission"
}

func (m *_BACnetPortPermission) GetLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(0)

	// Simple field (port)
	lengthInBits += m.Port.GetLengthInBits(ctx)

	// Optional Field (enable)
	if m.Enable != nil {
		lengthInBits += m.Enable.GetLengthInBits(ctx)
	}

	return lengthInBits
}

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

func BACnetPortPermissionParse(ctx context.Context, theBytes []byte) (BACnetPortPermission, error) {
	return BACnetPortPermissionParseWithBuffer(ctx, utils.NewReadBufferByteBased(theBytes))
}

func BACnetPortPermissionParseWithBufferProducer() func(ctx context.Context, readBuffer utils.ReadBuffer) (BACnetPortPermission, error) {
	return func(ctx context.Context, readBuffer utils.ReadBuffer) (BACnetPortPermission, error) {
		return BACnetPortPermissionParseWithBuffer(ctx, readBuffer)
	}
}

func BACnetPortPermissionParseWithBuffer(ctx context.Context, readBuffer utils.ReadBuffer) (BACnetPortPermission, error) {
	v, err := (new(_BACnetPortPermission)).parse(ctx, readBuffer)
	if err != nil {
		return nil, err
	}
	return v, nil
}

func (m *_BACnetPortPermission) parse(ctx context.Context, readBuffer utils.ReadBuffer) (__bACnetPortPermission BACnetPortPermission, err error) {
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("BACnetPortPermission"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for BACnetPortPermission")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

	port, err := ReadSimpleField[BACnetContextTagUnsignedInteger](ctx, "port", ReadComplex[BACnetContextTagUnsignedInteger](BACnetContextTagParseWithBufferProducer[BACnetContextTagUnsignedInteger]((uint8)(uint8(0)), (BACnetDataType)(BACnetDataType_UNSIGNED_INTEGER)), readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'port' field"))
	}
	m.Port = port

	var enable BACnetContextTagBoolean
	_enable, err := ReadOptionalField[BACnetContextTagBoolean](ctx, "enable", ReadComplex[BACnetContextTagBoolean](BACnetContextTagParseWithBufferProducer[BACnetContextTagBoolean]((uint8)(uint8(1)), (BACnetDataType)(BACnetDataType_BOOLEAN)), readBuffer), true)
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'enable' field"))
	}
	if _enable != nil {
		enable = *_enable
		m.Enable = enable
	}

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

	return m, nil
}

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

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

	if err := WriteOptionalField[BACnetContextTagBoolean](ctx, "enable", GetRef(m.GetEnable()), WriteComplex[BACnetContextTagBoolean](writeBuffer), true); err != nil {
		return errors.Wrap(err, "Error serializing 'enable' field")
	}

	if popErr := writeBuffer.PopContext("BACnetPortPermission"); popErr != nil {
		return errors.Wrap(popErr, "Error popping for BACnetPortPermission")
	}
	return nil
}

func (m *_BACnetPortPermission) IsBACnetPortPermission() {}

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

func (m *_BACnetPortPermission) deepCopy() *_BACnetPortPermission {
	if m == nil {
		return nil
	}
	_BACnetPortPermissionCopy := &_BACnetPortPermission{
		utils.DeepCopy[BACnetContextTagUnsignedInteger](m.Port),
		utils.DeepCopy[BACnetContextTagBoolean](m.Enable),
	}
	return _BACnetPortPermissionCopy
}

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