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

// ApduControl is the corresponding interface of ApduControl
type ApduControl interface {
	ApduControlContract
	ApduControlRequirements
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	// IsApduControl is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsApduControl()
	// CreateBuilder creates a ApduControlBuilder
	CreateApduControlBuilder() ApduControlBuilder
}

// ApduControlContract provides a set of functions which can be overwritten by a sub struct
type ApduControlContract interface {
	// IsApduControl is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsApduControl()
	// CreateBuilder creates a ApduControlBuilder
	CreateApduControlBuilder() ApduControlBuilder
}

// ApduControlRequirements provides a set of functions which need to be implemented by a sub struct
type ApduControlRequirements interface {
	GetLengthInBits(ctx context.Context) uint16
	GetLengthInBytes(ctx context.Context) uint16
	// GetControlType returns ControlType (discriminator field)
	GetControlType() uint8
}

// _ApduControl is the data-structure of this message
type _ApduControl struct {
	_SubType interface {
		ApduControlContract
		ApduControlRequirements
	}
}

var _ ApduControlContract = (*_ApduControl)(nil)

// NewApduControl factory function for _ApduControl
func NewApduControl() *_ApduControl {
	return &_ApduControl{}
}

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

// ApduControlBuilder is a builder for ApduControl
type ApduControlBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields() ApduControlBuilder
	// AsApduControlConnect converts this build to a subType of ApduControl. It is always possible to return to current builder using Done()
	AsApduControlConnect() ApduControlConnectBuilder
	// AsApduControlDisconnect converts this build to a subType of ApduControl. It is always possible to return to current builder using Done()
	AsApduControlDisconnect() ApduControlDisconnectBuilder
	// AsApduControlAck converts this build to a subType of ApduControl. It is always possible to return to current builder using Done()
	AsApduControlAck() ApduControlAckBuilder
	// AsApduControlNack converts this build to a subType of ApduControl. It is always possible to return to current builder using Done()
	AsApduControlNack() ApduControlNackBuilder
	// Build builds the ApduControl or returns an error if something is wrong
	PartialBuild() (ApduControlContract, error)
	// MustBuild does the same as Build but panics on error
	PartialMustBuild() ApduControlContract
	// Build builds the ApduControl or returns an error if something is wrong
	Build() (ApduControl, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() ApduControl
}

// NewApduControlBuilder() creates a ApduControlBuilder
func NewApduControlBuilder() ApduControlBuilder {
	return &_ApduControlBuilder{_ApduControl: new(_ApduControl)}
}

type _ApduControlChildBuilder interface {
	utils.Copyable
	setParent(ApduControlContract)
	buildForApduControl() (ApduControl, error)
}

type _ApduControlBuilder struct {
	*_ApduControl

	childBuilder _ApduControlChildBuilder

	collectedErr []error
}

var _ (ApduControlBuilder) = (*_ApduControlBuilder)(nil)

func (b *_ApduControlBuilder) WithMandatoryFields() ApduControlBuilder {
	return b
}

func (b *_ApduControlBuilder) PartialBuild() (ApduControlContract, error) {
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._ApduControl.deepCopy(), nil
}

func (b *_ApduControlBuilder) PartialMustBuild() ApduControlContract {
	build, err := b.PartialBuild()
	if err != nil {
		panic(err)
	}
	return build
}

func (b *_ApduControlBuilder) AsApduControlConnect() ApduControlConnectBuilder {
	if cb, ok := b.childBuilder.(ApduControlConnectBuilder); ok {
		return cb
	}
	cb := NewApduControlConnectBuilder().(*_ApduControlConnectBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_ApduControlBuilder) AsApduControlDisconnect() ApduControlDisconnectBuilder {
	if cb, ok := b.childBuilder.(ApduControlDisconnectBuilder); ok {
		return cb
	}
	cb := NewApduControlDisconnectBuilder().(*_ApduControlDisconnectBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_ApduControlBuilder) AsApduControlAck() ApduControlAckBuilder {
	if cb, ok := b.childBuilder.(ApduControlAckBuilder); ok {
		return cb
	}
	cb := NewApduControlAckBuilder().(*_ApduControlAckBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_ApduControlBuilder) AsApduControlNack() ApduControlNackBuilder {
	if cb, ok := b.childBuilder.(ApduControlNackBuilder); ok {
		return cb
	}
	cb := NewApduControlNackBuilder().(*_ApduControlNackBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_ApduControlBuilder) Build() (ApduControl, error) {
	v, err := b.PartialBuild()
	if err != nil {
		return nil, errors.Wrap(err, "error occurred during partial build")
	}
	if b.childBuilder == nil {
		return nil, errors.New("no child builder present")
	}
	b.childBuilder.setParent(v)
	return b.childBuilder.buildForApduControl()
}

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

func (b *_ApduControlBuilder) DeepCopy() any {
	_copy := b.CreateApduControlBuilder().(*_ApduControlBuilder)
	_copy.childBuilder = b.childBuilder.DeepCopy().(_ApduControlChildBuilder)
	_copy.childBuilder.setParent(_copy)
	if b.collectedErr != nil {
		copy(_copy.collectedErr, b.collectedErr)
	}
	return _copy
}

// CreateApduControlBuilder creates a ApduControlBuilder
func (b *_ApduControl) CreateApduControlBuilder() ApduControlBuilder {
	if b == nil {
		return NewApduControlBuilder()
	}
	return &_ApduControlBuilder{_ApduControl: b.deepCopy()}
}

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

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

func (m *_ApduControl) GetTypeName() string {
	return "ApduControl"
}

func (m *_ApduControl) getLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(0)
	// Discriminator Field (controlType)
	lengthInBits += 2

	return lengthInBits
}

func (m *_ApduControl) GetLengthInBits(ctx context.Context) uint16 {
	return m._SubType.GetLengthInBits(ctx)
}

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

func ApduControlParse[T ApduControl](ctx context.Context, theBytes []byte) (T, error) {
	return ApduControlParseWithBuffer[T](ctx, utils.NewReadBufferByteBased(theBytes))
}

func ApduControlParseWithBufferProducer[T ApduControl]() func(ctx context.Context, readBuffer utils.ReadBuffer) (T, error) {
	return func(ctx context.Context, readBuffer utils.ReadBuffer) (T, error) {
		v, err := ApduControlParseWithBuffer[T](ctx, readBuffer)
		if err != nil {
			var zero T
			return zero, err
		}
		return v, nil
	}
}

func ApduControlParseWithBuffer[T ApduControl](ctx context.Context, readBuffer utils.ReadBuffer) (T, error) {
	v, err := (new(_ApduControl)).parse(ctx, readBuffer)
	if err != nil {
		var zero T
		return zero, err
	}
	vc, ok := v.(T)
	if !ok {
		var zero T
		return zero, errors.Errorf("Unexpected type %T. Expected type %T", v, *new(T))
	}
	return vc, nil
}

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

	controlType, err := ReadDiscriminatorField[uint8](ctx, "controlType", ReadUnsignedByte(readBuffer, uint8(2)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'controlType' field"))
	}

	// Switch Field (Depending on the discriminator values, passes the instantiation to a sub-type)
	var _child ApduControl
	switch {
	case controlType == 0x0: // ApduControlConnect
		if _child, err = new(_ApduControlConnect).parse(ctx, readBuffer, m); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type ApduControlConnect for type-switch of ApduControl")
		}
	case controlType == 0x1: // ApduControlDisconnect
		if _child, err = new(_ApduControlDisconnect).parse(ctx, readBuffer, m); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type ApduControlDisconnect for type-switch of ApduControl")
		}
	case controlType == 0x2: // ApduControlAck
		if _child, err = new(_ApduControlAck).parse(ctx, readBuffer, m); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type ApduControlAck for type-switch of ApduControl")
		}
	case controlType == 0x3: // ApduControlNack
		if _child, err = new(_ApduControlNack).parse(ctx, readBuffer, m); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type ApduControlNack for type-switch of ApduControl")
		}
	default:
		return nil, errors.Errorf("Unmapped type for parameters [controlType=%v]", controlType)
	}

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

	return _child, nil
}

func (pm *_ApduControl) serializeParent(ctx context.Context, writeBuffer utils.WriteBuffer, child ApduControl, serializeChildFunction func() error) error {
	// We redirect all calls through client as some methods are only implemented there
	m := child
	_ = m
	positionAware := writeBuffer
	_ = positionAware
	log := zerolog.Ctx(ctx)
	_ = log
	if pushErr := writeBuffer.PushContext("ApduControl"); pushErr != nil {
		return errors.Wrap(pushErr, "Error pushing for ApduControl")
	}

	if err := WriteDiscriminatorField(ctx, "controlType", m.GetControlType(), WriteUnsignedByte(writeBuffer, 2)); err != nil {
		return errors.Wrap(err, "Error serializing 'controlType' field")
	}

	// Switch field (Depending on the discriminator values, passes the serialization to a sub-type)
	if _typeSwitchErr := serializeChildFunction(); _typeSwitchErr != nil {
		return errors.Wrap(_typeSwitchErr, "Error serializing sub-type field")
	}

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

func (m *_ApduControl) IsApduControl() {}

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

func (m *_ApduControl) deepCopy() *_ApduControl {
	if m == nil {
		return nil
	}
	_ApduControlCopy := &_ApduControl{
		nil, // will be set by child
	}
	return _ApduControlCopy
}
