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

// Payload is the corresponding interface of Payload
type Payload interface {
	PayloadContract
	PayloadRequirements
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	// IsPayload is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsPayload()
	// CreateBuilder creates a PayloadBuilder
	CreatePayloadBuilder() PayloadBuilder
}

// PayloadContract provides a set of functions which can be overwritten by a sub struct
type PayloadContract interface {
	// GetSequenceHeader returns SequenceHeader (property field)
	GetSequenceHeader() SequenceHeader
	// IsPayload is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsPayload()
	// CreateBuilder creates a PayloadBuilder
	CreatePayloadBuilder() PayloadBuilder
}

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

// _Payload is the data-structure of this message
type _Payload struct {
	_SubType interface {
		PayloadContract
		PayloadRequirements
	}
	SequenceHeader SequenceHeader
}

var _ PayloadContract = (*_Payload)(nil)

// NewPayload factory function for _Payload
func NewPayload(sequenceHeader SequenceHeader) *_Payload {
	if sequenceHeader == nil {
		panic("sequenceHeader of type SequenceHeader for Payload must not be nil")
	}
	return &_Payload{SequenceHeader: sequenceHeader}
}

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

// PayloadBuilder is a builder for Payload
type PayloadBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(sequenceHeader SequenceHeader) PayloadBuilder
	// WithSequenceHeader adds SequenceHeader (property field)
	WithSequenceHeader(SequenceHeader) PayloadBuilder
	// WithSequenceHeaderBuilder adds SequenceHeader (property field) which is build by the builder
	WithSequenceHeaderBuilder(func(SequenceHeaderBuilder) SequenceHeaderBuilder) PayloadBuilder
	// AsExtensiblePayload converts this build to a subType of Payload. It is always possible to return to current builder using Done()
	AsExtensiblePayload() ExtensiblePayloadBuilder
	// AsBinaryPayload converts this build to a subType of Payload. It is always possible to return to current builder using Done()
	AsBinaryPayload() BinaryPayloadBuilder
	// Build builds the Payload or returns an error if something is wrong
	PartialBuild() (PayloadContract, error)
	// MustBuild does the same as Build but panics on error
	PartialMustBuild() PayloadContract
	// Build builds the Payload or returns an error if something is wrong
	Build() (Payload, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() Payload
}

// NewPayloadBuilder() creates a PayloadBuilder
func NewPayloadBuilder() PayloadBuilder {
	return &_PayloadBuilder{_Payload: new(_Payload)}
}

type _PayloadChildBuilder interface {
	utils.Copyable
	setParent(PayloadContract)
	buildForPayload() (Payload, error)
}

type _PayloadBuilder struct {
	*_Payload

	childBuilder _PayloadChildBuilder

	collectedErr []error
}

var _ (PayloadBuilder) = (*_PayloadBuilder)(nil)

func (b *_PayloadBuilder) WithMandatoryFields(sequenceHeader SequenceHeader) PayloadBuilder {
	return b.WithSequenceHeader(sequenceHeader)
}

func (b *_PayloadBuilder) WithSequenceHeader(sequenceHeader SequenceHeader) PayloadBuilder {
	b.SequenceHeader = sequenceHeader
	return b
}

func (b *_PayloadBuilder) WithSequenceHeaderBuilder(builderSupplier func(SequenceHeaderBuilder) SequenceHeaderBuilder) PayloadBuilder {
	builder := builderSupplier(b.SequenceHeader.CreateSequenceHeaderBuilder())
	var err error
	b.SequenceHeader, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "SequenceHeaderBuilder failed"))
	}
	return b
}

func (b *_PayloadBuilder) PartialBuild() (PayloadContract, error) {
	if b.SequenceHeader == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'sequenceHeader' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._Payload.deepCopy(), nil
}

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

func (b *_PayloadBuilder) AsExtensiblePayload() ExtensiblePayloadBuilder {
	if cb, ok := b.childBuilder.(ExtensiblePayloadBuilder); ok {
		return cb
	}
	cb := NewExtensiblePayloadBuilder().(*_ExtensiblePayloadBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_PayloadBuilder) AsBinaryPayload() BinaryPayloadBuilder {
	if cb, ok := b.childBuilder.(BinaryPayloadBuilder); ok {
		return cb
	}
	cb := NewBinaryPayloadBuilder().(*_BinaryPayloadBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_PayloadBuilder) Build() (Payload, 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.buildForPayload()
}

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

func (b *_PayloadBuilder) DeepCopy() any {
	_copy := b.CreatePayloadBuilder().(*_PayloadBuilder)
	_copy.childBuilder = b.childBuilder.DeepCopy().(_PayloadChildBuilder)
	_copy.childBuilder.setParent(_copy)
	if b.collectedErr != nil {
		copy(_copy.collectedErr, b.collectedErr)
	}
	return _copy
}

// CreatePayloadBuilder creates a PayloadBuilder
func (b *_Payload) CreatePayloadBuilder() PayloadBuilder {
	if b == nil {
		return NewPayloadBuilder()
	}
	return &_PayloadBuilder{_Payload: b.deepCopy()}
}

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

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

func (m *_Payload) GetSequenceHeader() SequenceHeader {
	return m.SequenceHeader
}

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

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

func (m *_Payload) GetTypeName() string {
	return "Payload"
}

func (m *_Payload) getLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(0)

	// Simple field (sequenceHeader)
	lengthInBits += m.SequenceHeader.GetLengthInBits(ctx)

	return lengthInBits
}

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

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

func PayloadParse[T Payload](ctx context.Context, theBytes []byte, binary bool, byteCount uint32) (T, error) {
	return PayloadParseWithBuffer[T](ctx, utils.NewReadBufferByteBased(theBytes), binary, byteCount)
}

func PayloadParseWithBufferProducer[T Payload](binary bool, byteCount uint32) func(ctx context.Context, readBuffer utils.ReadBuffer) (T, error) {
	return func(ctx context.Context, readBuffer utils.ReadBuffer) (T, error) {
		v, err := PayloadParseWithBuffer[T](ctx, readBuffer, binary, byteCount)
		if err != nil {
			var zero T
			return zero, err
		}
		return v, nil
	}
}

func PayloadParseWithBuffer[T Payload](ctx context.Context, readBuffer utils.ReadBuffer, binary bool, byteCount uint32) (T, error) {
	v, err := (new(_Payload)).parse(ctx, readBuffer, binary, byteCount)
	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 *_Payload) parse(ctx context.Context, readBuffer utils.ReadBuffer, binary bool, byteCount uint32) (__payload Payload, err error) {
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("Payload"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for Payload")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

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

	// Switch Field (Depending on the discriminator values, passes the instantiation to a sub-type)
	var _child Payload
	switch {
	case binary == bool(false): // ExtensiblePayload
		if _child, err = new(_ExtensiblePayload).parse(ctx, readBuffer, m, binary, byteCount); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type ExtensiblePayload for type-switch of Payload")
		}
	case binary == bool(true): // BinaryPayload
		if _child, err = new(_BinaryPayload).parse(ctx, readBuffer, m, binary, byteCount); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type BinaryPayload for type-switch of Payload")
		}
	default:
		return nil, errors.Errorf("Unmapped type for parameters [binary=%v]", binary)
	}

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

	return _child, nil
}

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

	if err := WriteSimpleField[SequenceHeader](ctx, "sequenceHeader", m.GetSequenceHeader(), WriteComplex[SequenceHeader](writeBuffer)); err != nil {
		return errors.Wrap(err, "Error serializing 'sequenceHeader' 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("Payload"); popErr != nil {
		return errors.Wrap(popErr, "Error popping for Payload")
	}
	return nil
}

func (m *_Payload) IsPayload() {}

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

func (m *_Payload) deepCopy() *_Payload {
	if m == nil {
		return nil
	}
	_PayloadCopy := &_Payload{
		nil, // will be set by child
		utils.DeepCopy[SequenceHeader](m.SequenceHeader),
	}
	return _PayloadCopy
}
