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

// ApduControlContainer is the corresponding interface of ApduControlContainer
type ApduControlContainer interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	Apdu
	// GetControlApdu returns ControlApdu (property field)
	GetControlApdu() ApduControl
	// IsApduControlContainer is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsApduControlContainer()
	// CreateBuilder creates a ApduControlContainerBuilder
	CreateApduControlContainerBuilder() ApduControlContainerBuilder
}

// _ApduControlContainer is the data-structure of this message
type _ApduControlContainer struct {
	ApduContract
	ControlApdu ApduControl
}

var _ ApduControlContainer = (*_ApduControlContainer)(nil)
var _ ApduRequirements = (*_ApduControlContainer)(nil)

// NewApduControlContainer factory function for _ApduControlContainer
func NewApduControlContainer(numbered bool, counter uint8, controlApdu ApduControl) *_ApduControlContainer {
	if controlApdu == nil {
		panic("controlApdu of type ApduControl for ApduControlContainer must not be nil")
	}
	_result := &_ApduControlContainer{
		ApduContract: NewApdu(numbered, counter),
		ControlApdu:  controlApdu,
	}
	_result.ApduContract.(*_Apdu)._SubType = _result
	return _result
}

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

// ApduControlContainerBuilder is a builder for ApduControlContainer
type ApduControlContainerBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(controlApdu ApduControl) ApduControlContainerBuilder
	// WithControlApdu adds ControlApdu (property field)
	WithControlApdu(ApduControl) ApduControlContainerBuilder
	// WithControlApduBuilder adds ControlApdu (property field) which is build by the builder
	WithControlApduBuilder(func(ApduControlBuilder) ApduControlBuilder) ApduControlContainerBuilder
	// Done is used to finish work on this child and return (or create one if none) to the parent builder
	Done() ApduBuilder
	// Build builds the ApduControlContainer or returns an error if something is wrong
	Build() (ApduControlContainer, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() ApduControlContainer
}

// NewApduControlContainerBuilder() creates a ApduControlContainerBuilder
func NewApduControlContainerBuilder() ApduControlContainerBuilder {
	return &_ApduControlContainerBuilder{_ApduControlContainer: new(_ApduControlContainer)}
}

type _ApduControlContainerBuilder struct {
	*_ApduControlContainer

	parentBuilder *_ApduBuilder

	collectedErr []error
}

var _ (ApduControlContainerBuilder) = (*_ApduControlContainerBuilder)(nil)

func (b *_ApduControlContainerBuilder) setParent(contract ApduContract) {
	b.ApduContract = contract
	contract.(*_Apdu)._SubType = b._ApduControlContainer
}

func (b *_ApduControlContainerBuilder) WithMandatoryFields(controlApdu ApduControl) ApduControlContainerBuilder {
	return b.WithControlApdu(controlApdu)
}

func (b *_ApduControlContainerBuilder) WithControlApdu(controlApdu ApduControl) ApduControlContainerBuilder {
	b.ControlApdu = controlApdu
	return b
}

func (b *_ApduControlContainerBuilder) WithControlApduBuilder(builderSupplier func(ApduControlBuilder) ApduControlBuilder) ApduControlContainerBuilder {
	builder := builderSupplier(b.ControlApdu.CreateApduControlBuilder())
	var err error
	b.ControlApdu, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "ApduControlBuilder failed"))
	}
	return b
}

func (b *_ApduControlContainerBuilder) Build() (ApduControlContainer, error) {
	if b.ControlApdu == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'controlApdu' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._ApduControlContainer.deepCopy(), nil
}

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

func (b *_ApduControlContainerBuilder) Done() ApduBuilder {
	if b.parentBuilder == nil {
		b.parentBuilder = NewApduBuilder().(*_ApduBuilder)
	}
	return b.parentBuilder
}

func (b *_ApduControlContainerBuilder) buildForApdu() (Apdu, error) {
	return b.Build()
}

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

// CreateApduControlContainerBuilder creates a ApduControlContainerBuilder
func (b *_ApduControlContainer) CreateApduControlContainerBuilder() ApduControlContainerBuilder {
	if b == nil {
		return NewApduControlContainerBuilder()
	}
	return &_ApduControlContainerBuilder{_ApduControlContainer: b.deepCopy()}
}

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

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

func (m *_ApduControlContainer) GetControl() uint8 {
	return uint8(1)
}

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

func (m *_ApduControlContainer) GetParent() ApduContract {
	return m.ApduContract
}

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

func (m *_ApduControlContainer) GetControlApdu() ApduControl {
	return m.ControlApdu
}

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

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

func (m *_ApduControlContainer) GetTypeName() string {
	return "ApduControlContainer"
}

func (m *_ApduControlContainer) GetLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(m.ApduContract.(*_Apdu).getLengthInBits(ctx))

	// Simple field (controlApdu)
	lengthInBits += m.ControlApdu.GetLengthInBits(ctx)

	return lengthInBits
}

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

func (m *_ApduControlContainer) parse(ctx context.Context, readBuffer utils.ReadBuffer, parent *_Apdu, dataLength uint8) (__apduControlContainer ApduControlContainer, err error) {
	m.ApduContract = parent
	parent._SubType = m
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("ApduControlContainer"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for ApduControlContainer")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

	controlApdu, err := ReadSimpleField[ApduControl](ctx, "controlApdu", ReadComplex[ApduControl](ApduControlParseWithBuffer, readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'controlApdu' field"))
	}
	m.ControlApdu = controlApdu

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

	return m, nil
}

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

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

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

func (m *_ApduControlContainer) IsApduControlContainer() {}

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

func (m *_ApduControlContainer) deepCopy() *_ApduControlContainer {
	if m == nil {
		return nil
	}
	_ApduControlContainerCopy := &_ApduControlContainer{
		m.ApduContract.(*_Apdu).deepCopy(),
		utils.DeepCopy[ApduControl](m.ControlApdu),
	}
	_ApduControlContainerCopy.ApduContract.(*_Apdu)._SubType = m
	return _ApduControlContainerCopy
}

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