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

// APDU is the corresponding interface of APDU
type APDU interface {
	APDUContract
	APDURequirements
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	// IsAPDU is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsAPDU()
	// CreateBuilder creates a APDUBuilder
	CreateAPDUBuilder() APDUBuilder
}

// APDUContract provides a set of functions which can be overwritten by a sub struct
type APDUContract interface {
	// IsAPDU is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsAPDU()
	// CreateBuilder creates a APDUBuilder
	CreateAPDUBuilder() APDUBuilder
}

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

// _APDU is the data-structure of this message
type _APDU struct {
	_SubType interface {
		APDUContract
		APDURequirements
	}
}

var _ APDUContract = (*_APDU)(nil)

// NewAPDU factory function for _APDU
func NewAPDU() *_APDU {
	return &_APDU{}
}

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

// APDUBuilder is a builder for APDU
type APDUBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields() APDUBuilder
	// AsAPDUConfirmedRequest converts this build to a subType of APDU. It is always possible to return to current builder using Done()
	AsAPDUConfirmedRequest() APDUConfirmedRequestBuilder
	// AsAPDUUnconfirmedRequest converts this build to a subType of APDU. It is always possible to return to current builder using Done()
	AsAPDUUnconfirmedRequest() APDUUnconfirmedRequestBuilder
	// AsAPDUSimpleAck converts this build to a subType of APDU. It is always possible to return to current builder using Done()
	AsAPDUSimpleAck() APDUSimpleAckBuilder
	// AsAPDUComplexAck converts this build to a subType of APDU. It is always possible to return to current builder using Done()
	AsAPDUComplexAck() APDUComplexAckBuilder
	// AsAPDUSegmentAck converts this build to a subType of APDU. It is always possible to return to current builder using Done()
	AsAPDUSegmentAck() APDUSegmentAckBuilder
	// AsAPDUError converts this build to a subType of APDU. It is always possible to return to current builder using Done()
	AsAPDUError() APDUErrorBuilder
	// AsAPDUReject converts this build to a subType of APDU. It is always possible to return to current builder using Done()
	AsAPDUReject() APDURejectBuilder
	// AsAPDUAbort converts this build to a subType of APDU. It is always possible to return to current builder using Done()
	AsAPDUAbort() APDUAbortBuilder
	// AsAPDUUnknown converts this build to a subType of APDU. It is always possible to return to current builder using Done()
	AsAPDUUnknown() APDUUnknownBuilder
	// Build builds the APDU or returns an error if something is wrong
	PartialBuild() (APDUContract, error)
	// MustBuild does the same as Build but panics on error
	PartialMustBuild() APDUContract
	// Build builds the APDU or returns an error if something is wrong
	Build() (APDU, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() APDU
}

// NewAPDUBuilder() creates a APDUBuilder
func NewAPDUBuilder() APDUBuilder {
	return &_APDUBuilder{_APDU: new(_APDU)}
}

type _APDUChildBuilder interface {
	utils.Copyable
	setParent(APDUContract)
	buildForAPDU() (APDU, error)
}

type _APDUBuilder struct {
	*_APDU

	childBuilder _APDUChildBuilder

	collectedErr []error
}

var _ (APDUBuilder) = (*_APDUBuilder)(nil)

func (b *_APDUBuilder) WithMandatoryFields() APDUBuilder {
	return b
}

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

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

func (b *_APDUBuilder) AsAPDUConfirmedRequest() APDUConfirmedRequestBuilder {
	if cb, ok := b.childBuilder.(APDUConfirmedRequestBuilder); ok {
		return cb
	}
	cb := NewAPDUConfirmedRequestBuilder().(*_APDUConfirmedRequestBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_APDUBuilder) AsAPDUUnconfirmedRequest() APDUUnconfirmedRequestBuilder {
	if cb, ok := b.childBuilder.(APDUUnconfirmedRequestBuilder); ok {
		return cb
	}
	cb := NewAPDUUnconfirmedRequestBuilder().(*_APDUUnconfirmedRequestBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_APDUBuilder) AsAPDUSimpleAck() APDUSimpleAckBuilder {
	if cb, ok := b.childBuilder.(APDUSimpleAckBuilder); ok {
		return cb
	}
	cb := NewAPDUSimpleAckBuilder().(*_APDUSimpleAckBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_APDUBuilder) AsAPDUComplexAck() APDUComplexAckBuilder {
	if cb, ok := b.childBuilder.(APDUComplexAckBuilder); ok {
		return cb
	}
	cb := NewAPDUComplexAckBuilder().(*_APDUComplexAckBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_APDUBuilder) AsAPDUSegmentAck() APDUSegmentAckBuilder {
	if cb, ok := b.childBuilder.(APDUSegmentAckBuilder); ok {
		return cb
	}
	cb := NewAPDUSegmentAckBuilder().(*_APDUSegmentAckBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_APDUBuilder) AsAPDUError() APDUErrorBuilder {
	if cb, ok := b.childBuilder.(APDUErrorBuilder); ok {
		return cb
	}
	cb := NewAPDUErrorBuilder().(*_APDUErrorBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_APDUBuilder) AsAPDUReject() APDURejectBuilder {
	if cb, ok := b.childBuilder.(APDURejectBuilder); ok {
		return cb
	}
	cb := NewAPDURejectBuilder().(*_APDURejectBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_APDUBuilder) AsAPDUAbort() APDUAbortBuilder {
	if cb, ok := b.childBuilder.(APDUAbortBuilder); ok {
		return cb
	}
	cb := NewAPDUAbortBuilder().(*_APDUAbortBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_APDUBuilder) AsAPDUUnknown() APDUUnknownBuilder {
	if cb, ok := b.childBuilder.(APDUUnknownBuilder); ok {
		return cb
	}
	cb := NewAPDUUnknownBuilder().(*_APDUUnknownBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_APDUBuilder) Build() (APDU, 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.buildForAPDU()
}

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

func (b *_APDUBuilder) DeepCopy() any {
	_copy := b.CreateAPDUBuilder().(*_APDUBuilder)
	_copy.childBuilder = b.childBuilder.DeepCopy().(_APDUChildBuilder)
	_copy.childBuilder.setParent(_copy)
	if b.collectedErr != nil {
		copy(_copy.collectedErr, b.collectedErr)
	}
	return _copy
}

// CreateAPDUBuilder creates a APDUBuilder
func (b *_APDU) CreateAPDUBuilder() APDUBuilder {
	if b == nil {
		return NewAPDUBuilder()
	}
	return &_APDUBuilder{_APDU: b.deepCopy()}
}

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

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

func (m *_APDU) GetTypeName() string {
	return "APDU"
}

func (m *_APDU) getLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(0)
	// Discriminator Field (apduType)
	lengthInBits += 4

	return lengthInBits
}

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

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

func APDUParse[T APDU](ctx context.Context, theBytes []byte, apduLength uint16) (T, error) {
	return APDUParseWithBuffer[T](ctx, utils.NewReadBufferByteBased(theBytes), apduLength)
}

func APDUParseWithBufferProducer[T APDU](apduLength uint16) func(ctx context.Context, readBuffer utils.ReadBuffer) (T, error) {
	return func(ctx context.Context, readBuffer utils.ReadBuffer) (T, error) {
		v, err := APDUParseWithBuffer[T](ctx, readBuffer, apduLength)
		if err != nil {
			var zero T
			return zero, err
		}
		return v, nil
	}
}

func APDUParseWithBuffer[T APDU](ctx context.Context, readBuffer utils.ReadBuffer, apduLength uint16) (T, error) {
	v, err := (new(_APDU)).parse(ctx, readBuffer, apduLength)
	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 *_APDU) parse(ctx context.Context, readBuffer utils.ReadBuffer, apduLength uint16) (__aPDU APDU, err error) {
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("APDU"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for APDU")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

	apduType, err := ReadDiscriminatorEnumField[ApduType](ctx, "apduType", "ApduType", ReadEnum(ApduTypeByValue, ReadUnsignedByte(readBuffer, uint8(4))))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'apduType' field"))
	}

	// Switch Field (Depending on the discriminator values, passes the instantiation to a sub-type)
	var _child APDU
	switch {
	case apduType == ApduType_CONFIRMED_REQUEST_PDU: // APDUConfirmedRequest
		if _child, err = new(_APDUConfirmedRequest).parse(ctx, readBuffer, m, apduLength); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type APDUConfirmedRequest for type-switch of APDU")
		}
	case apduType == ApduType_UNCONFIRMED_REQUEST_PDU: // APDUUnconfirmedRequest
		if _child, err = new(_APDUUnconfirmedRequest).parse(ctx, readBuffer, m, apduLength); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type APDUUnconfirmedRequest for type-switch of APDU")
		}
	case apduType == ApduType_SIMPLE_ACK_PDU: // APDUSimpleAck
		if _child, err = new(_APDUSimpleAck).parse(ctx, readBuffer, m, apduLength); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type APDUSimpleAck for type-switch of APDU")
		}
	case apduType == ApduType_COMPLEX_ACK_PDU: // APDUComplexAck
		if _child, err = new(_APDUComplexAck).parse(ctx, readBuffer, m, apduLength); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type APDUComplexAck for type-switch of APDU")
		}
	case apduType == ApduType_SEGMENT_ACK_PDU: // APDUSegmentAck
		if _child, err = new(_APDUSegmentAck).parse(ctx, readBuffer, m, apduLength); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type APDUSegmentAck for type-switch of APDU")
		}
	case apduType == ApduType_ERROR_PDU: // APDUError
		if _child, err = new(_APDUError).parse(ctx, readBuffer, m, apduLength); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type APDUError for type-switch of APDU")
		}
	case apduType == ApduType_REJECT_PDU: // APDUReject
		if _child, err = new(_APDUReject).parse(ctx, readBuffer, m, apduLength); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type APDUReject for type-switch of APDU")
		}
	case apduType == ApduType_ABORT_PDU: // APDUAbort
		if _child, err = new(_APDUAbort).parse(ctx, readBuffer, m, apduLength); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type APDUAbort for type-switch of APDU")
		}
	case 0 == 0: // APDUUnknown
		if _child, err = new(_APDUUnknown).parse(ctx, readBuffer, m, apduLength); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type APDUUnknown for type-switch of APDU")
		}
	default:
		return nil, errors.Errorf("Unmapped type for parameters [apduType=%v]", apduType)
	}

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

	return _child, nil
}

func (pm *_APDU) serializeParent(ctx context.Context, writeBuffer utils.WriteBuffer, child APDU, 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("APDU"); pushErr != nil {
		return errors.Wrap(pushErr, "Error pushing for APDU")
	}

	if err := WriteDiscriminatorEnumField(ctx, "apduType", "ApduType", m.GetApduType(), WriteEnum[ApduType, uint8](ApduType.GetValue, ApduType.PLC4XEnumName, WriteUnsignedByte(writeBuffer, 4))); err != nil {
		return errors.Wrap(err, "Error serializing 'apduType' 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("APDU"); popErr != nil {
		return errors.Wrap(popErr, "Error popping for APDU")
	}
	return nil
}

func (m *_APDU) IsAPDU() {}

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

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