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

// BACnetContextTagCharacterString is the corresponding interface of BACnetContextTagCharacterString
type BACnetContextTagCharacterString interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	BACnetContextTag
	// GetPayload returns Payload (property field)
	GetPayload() BACnetTagPayloadCharacterString
	// GetValue returns Value (virtual field)
	GetValue() string
	// IsBACnetContextTagCharacterString is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsBACnetContextTagCharacterString()
	// CreateBuilder creates a BACnetContextTagCharacterStringBuilder
	CreateBACnetContextTagCharacterStringBuilder() BACnetContextTagCharacterStringBuilder
}

// _BACnetContextTagCharacterString is the data-structure of this message
type _BACnetContextTagCharacterString struct {
	BACnetContextTagContract
	Payload BACnetTagPayloadCharacterString
}

var _ BACnetContextTagCharacterString = (*_BACnetContextTagCharacterString)(nil)
var _ BACnetContextTagRequirements = (*_BACnetContextTagCharacterString)(nil)

// NewBACnetContextTagCharacterString factory function for _BACnetContextTagCharacterString
func NewBACnetContextTagCharacterString(header BACnetTagHeader, payload BACnetTagPayloadCharacterString) *_BACnetContextTagCharacterString {
	if payload == nil {
		panic("payload of type BACnetTagPayloadCharacterString for BACnetContextTagCharacterString must not be nil")
	}
	_result := &_BACnetContextTagCharacterString{
		BACnetContextTagContract: NewBACnetContextTag(header),
		Payload:                  payload,
	}
	_result.BACnetContextTagContract.(*_BACnetContextTag)._SubType = _result
	return _result
}

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

// BACnetContextTagCharacterStringBuilder is a builder for BACnetContextTagCharacterString
type BACnetContextTagCharacterStringBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(payload BACnetTagPayloadCharacterString) BACnetContextTagCharacterStringBuilder
	// WithPayload adds Payload (property field)
	WithPayload(BACnetTagPayloadCharacterString) BACnetContextTagCharacterStringBuilder
	// WithPayloadBuilder adds Payload (property field) which is build by the builder
	WithPayloadBuilder(func(BACnetTagPayloadCharacterStringBuilder) BACnetTagPayloadCharacterStringBuilder) BACnetContextTagCharacterStringBuilder
	// Done is used to finish work on this child and return (or create one if none) to the parent builder
	Done() BACnetContextTagBuilder
	// Build builds the BACnetContextTagCharacterString or returns an error if something is wrong
	Build() (BACnetContextTagCharacterString, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() BACnetContextTagCharacterString
}

// NewBACnetContextTagCharacterStringBuilder() creates a BACnetContextTagCharacterStringBuilder
func NewBACnetContextTagCharacterStringBuilder() BACnetContextTagCharacterStringBuilder {
	return &_BACnetContextTagCharacterStringBuilder{_BACnetContextTagCharacterString: new(_BACnetContextTagCharacterString)}
}

type _BACnetContextTagCharacterStringBuilder struct {
	*_BACnetContextTagCharacterString

	parentBuilder *_BACnetContextTagBuilder

	collectedErr []error
}

var _ (BACnetContextTagCharacterStringBuilder) = (*_BACnetContextTagCharacterStringBuilder)(nil)

func (b *_BACnetContextTagCharacterStringBuilder) setParent(contract BACnetContextTagContract) {
	b.BACnetContextTagContract = contract
	contract.(*_BACnetContextTag)._SubType = b._BACnetContextTagCharacterString
}

func (b *_BACnetContextTagCharacterStringBuilder) WithMandatoryFields(payload BACnetTagPayloadCharacterString) BACnetContextTagCharacterStringBuilder {
	return b.WithPayload(payload)
}

func (b *_BACnetContextTagCharacterStringBuilder) WithPayload(payload BACnetTagPayloadCharacterString) BACnetContextTagCharacterStringBuilder {
	b.Payload = payload
	return b
}

func (b *_BACnetContextTagCharacterStringBuilder) WithPayloadBuilder(builderSupplier func(BACnetTagPayloadCharacterStringBuilder) BACnetTagPayloadCharacterStringBuilder) BACnetContextTagCharacterStringBuilder {
	builder := builderSupplier(b.Payload.CreateBACnetTagPayloadCharacterStringBuilder())
	var err error
	b.Payload, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "BACnetTagPayloadCharacterStringBuilder failed"))
	}
	return b
}

func (b *_BACnetContextTagCharacterStringBuilder) Build() (BACnetContextTagCharacterString, error) {
	if b.Payload == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'payload' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._BACnetContextTagCharacterString.deepCopy(), nil
}

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

func (b *_BACnetContextTagCharacterStringBuilder) Done() BACnetContextTagBuilder {
	if b.parentBuilder == nil {
		b.parentBuilder = NewBACnetContextTagBuilder().(*_BACnetContextTagBuilder)
	}
	return b.parentBuilder
}

func (b *_BACnetContextTagCharacterStringBuilder) buildForBACnetContextTag() (BACnetContextTag, error) {
	return b.Build()
}

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

// CreateBACnetContextTagCharacterStringBuilder creates a BACnetContextTagCharacterStringBuilder
func (b *_BACnetContextTagCharacterString) CreateBACnetContextTagCharacterStringBuilder() BACnetContextTagCharacterStringBuilder {
	if b == nil {
		return NewBACnetContextTagCharacterStringBuilder()
	}
	return &_BACnetContextTagCharacterStringBuilder{_BACnetContextTagCharacterString: b.deepCopy()}
}

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

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

func (m *_BACnetContextTagCharacterString) GetDataType() BACnetDataType {
	return BACnetDataType_CHARACTER_STRING
}

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

func (m *_BACnetContextTagCharacterString) GetParent() BACnetContextTagContract {
	return m.BACnetContextTagContract
}

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

func (m *_BACnetContextTagCharacterString) GetPayload() BACnetTagPayloadCharacterString {
	return m.Payload
}

///////////////////////
///////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/////////////////////// Accessors for virtual fields.
///////////////////////

func (m *_BACnetContextTagCharacterString) GetValue() string {
	ctx := context.Background()
	_ = ctx
	return fmt.Sprintf("%v", m.GetPayload().GetValue())
}

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

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

func (m *_BACnetContextTagCharacterString) GetTypeName() string {
	return "BACnetContextTagCharacterString"
}

func (m *_BACnetContextTagCharacterString) GetLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(m.BACnetContextTagContract.(*_BACnetContextTag).getLengthInBits(ctx))

	// Simple field (payload)
	lengthInBits += m.Payload.GetLengthInBits(ctx)

	// A virtual field doesn't have any in- or output.

	return lengthInBits
}

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

func (m *_BACnetContextTagCharacterString) parse(ctx context.Context, readBuffer utils.ReadBuffer, parent *_BACnetContextTag, header BACnetTagHeader, tagNumberArgument uint8, dataType BACnetDataType) (__bACnetContextTagCharacterString BACnetContextTagCharacterString, err error) {
	m.BACnetContextTagContract = parent
	parent._SubType = m
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("BACnetContextTagCharacterString"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for BACnetContextTagCharacterString")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

	payload, err := ReadSimpleField[BACnetTagPayloadCharacterString](ctx, "payload", ReadComplex[BACnetTagPayloadCharacterString](BACnetTagPayloadCharacterStringParseWithBufferProducer((uint32)(header.GetActualLength())), readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'payload' field"))
	}
	m.Payload = payload

	value, err := ReadVirtualField[string](ctx, "value", (*string)(nil), payload.GetValue())
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'value' field"))
	}
	_ = value

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

	return m, nil
}

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

		if err := WriteSimpleField[BACnetTagPayloadCharacterString](ctx, "payload", m.GetPayload(), WriteComplex[BACnetTagPayloadCharacterString](writeBuffer)); err != nil {
			return errors.Wrap(err, "Error serializing 'payload' field")
		}
		// Virtual field
		value := m.GetValue()
		_ = value
		if _valueErr := writeBuffer.WriteVirtual(ctx, "value", m.GetValue()); _valueErr != nil {
			return errors.Wrap(_valueErr, "Error serializing 'value' field")
		}

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

func (m *_BACnetContextTagCharacterString) IsBACnetContextTagCharacterString() {}

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

func (m *_BACnetContextTagCharacterString) deepCopy() *_BACnetContextTagCharacterString {
	if m == nil {
		return nil
	}
	_BACnetContextTagCharacterStringCopy := &_BACnetContextTagCharacterString{
		m.BACnetContextTagContract.(*_BACnetContextTag).deepCopy(),
		utils.DeepCopy[BACnetTagPayloadCharacterString](m.Payload),
	}
	_BACnetContextTagCharacterStringCopy.BACnetContextTagContract.(*_BACnetContextTag)._SubType = m
	return _BACnetContextTagCharacterStringCopy
}

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