/*
 * 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"
	"fmt"

	"github.com/pkg/errors"
	"github.com/rs/zerolog"

	"github.com/apache/plc4x/plc4go/spi/utils"
)

// Code generated by code-generation. DO NOT EDIT.

// S7Payload is the corresponding interface of S7Payload
type S7Payload interface {
	S7PayloadContract
	S7PayloadRequirements
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	// IsS7Payload is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsS7Payload()
	// CreateBuilder creates a S7PayloadBuilder
	CreateS7PayloadBuilder() S7PayloadBuilder
}

// S7PayloadContract provides a set of functions which can be overwritten by a sub struct
type S7PayloadContract interface {
	// GetParameter() returns a parser argument
	GetParameter() S7Parameter
	// IsS7Payload is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsS7Payload()
	// CreateBuilder creates a S7PayloadBuilder
	CreateS7PayloadBuilder() S7PayloadBuilder
}

// S7PayloadRequirements provides a set of functions which need to be implemented by a sub struct
type S7PayloadRequirements interface {
	GetLengthInBits(ctx context.Context) uint16
	GetLengthInBytes(ctx context.Context) uint16
	// GetMessageType returns MessageType (discriminator field)
	GetMessageType() uint8
	// GetParameterParameterType returns ParameterParameterType (discriminator field)
	GetParameterParameterType() uint8
}

// _S7Payload is the data-structure of this message
type _S7Payload struct {
	_SubType interface {
		S7PayloadContract
		S7PayloadRequirements
	}

	// Arguments.
	Parameter S7Parameter
}

var _ S7PayloadContract = (*_S7Payload)(nil)

// NewS7Payload factory function for _S7Payload
func NewS7Payload(parameter S7Parameter) *_S7Payload {
	return &_S7Payload{Parameter: parameter}
}

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

// S7PayloadBuilder is a builder for S7Payload
type S7PayloadBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields() S7PayloadBuilder
	// WithArgParameter sets a parser argument
	WithArgParameter(S7Parameter) S7PayloadBuilder
	// AsS7PayloadReadVarResponse converts this build to a subType of S7Payload. It is always possible to return to current builder using Done()
	AsS7PayloadReadVarResponse() S7PayloadReadVarResponseBuilder
	// AsS7PayloadWriteVarRequest converts this build to a subType of S7Payload. It is always possible to return to current builder using Done()
	AsS7PayloadWriteVarRequest() S7PayloadWriteVarRequestBuilder
	// AsS7PayloadWriteVarResponse converts this build to a subType of S7Payload. It is always possible to return to current builder using Done()
	AsS7PayloadWriteVarResponse() S7PayloadWriteVarResponseBuilder
	// AsS7PayloadUserData converts this build to a subType of S7Payload. It is always possible to return to current builder using Done()
	AsS7PayloadUserData() S7PayloadUserDataBuilder
	// Build builds the S7Payload or returns an error if something is wrong
	PartialBuild() (S7PayloadContract, error)
	// MustBuild does the same as Build but panics on error
	PartialMustBuild() S7PayloadContract
	// Build builds the S7Payload or returns an error if something is wrong
	Build() (S7Payload, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() S7Payload
}

// NewS7PayloadBuilder() creates a S7PayloadBuilder
func NewS7PayloadBuilder() S7PayloadBuilder {
	return &_S7PayloadBuilder{_S7Payload: new(_S7Payload)}
}

type _S7PayloadChildBuilder interface {
	utils.Copyable
	setParent(S7PayloadContract)
	buildForS7Payload() (S7Payload, error)
}

type _S7PayloadBuilder struct {
	*_S7Payload

	childBuilder _S7PayloadChildBuilder

	err *utils.MultiError
}

var _ (S7PayloadBuilder) = (*_S7PayloadBuilder)(nil)

func (b *_S7PayloadBuilder) WithMandatoryFields() S7PayloadBuilder {
	return b
}

func (b *_S7PayloadBuilder) WithArgParameter(parameter S7Parameter) S7PayloadBuilder {
	b.Parameter = parameter
	return b
}

func (b *_S7PayloadBuilder) PartialBuild() (S7PayloadContract, error) {
	if b.err != nil {
		return nil, errors.Wrap(b.err, "error occurred during build")
	}
	return b._S7Payload.deepCopy(), nil
}

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

func (b *_S7PayloadBuilder) AsS7PayloadReadVarResponse() S7PayloadReadVarResponseBuilder {
	if cb, ok := b.childBuilder.(S7PayloadReadVarResponseBuilder); ok {
		return cb
	}
	cb := NewS7PayloadReadVarResponseBuilder().(*_S7PayloadReadVarResponseBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_S7PayloadBuilder) AsS7PayloadWriteVarRequest() S7PayloadWriteVarRequestBuilder {
	if cb, ok := b.childBuilder.(S7PayloadWriteVarRequestBuilder); ok {
		return cb
	}
	cb := NewS7PayloadWriteVarRequestBuilder().(*_S7PayloadWriteVarRequestBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_S7PayloadBuilder) AsS7PayloadWriteVarResponse() S7PayloadWriteVarResponseBuilder {
	if cb, ok := b.childBuilder.(S7PayloadWriteVarResponseBuilder); ok {
		return cb
	}
	cb := NewS7PayloadWriteVarResponseBuilder().(*_S7PayloadWriteVarResponseBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_S7PayloadBuilder) AsS7PayloadUserData() S7PayloadUserDataBuilder {
	if cb, ok := b.childBuilder.(S7PayloadUserDataBuilder); ok {
		return cb
	}
	cb := NewS7PayloadUserDataBuilder().(*_S7PayloadUserDataBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_S7PayloadBuilder) Build() (S7Payload, 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.buildForS7Payload()
}

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

func (b *_S7PayloadBuilder) DeepCopy() any {
	_copy := b.CreateS7PayloadBuilder().(*_S7PayloadBuilder)
	_copy.childBuilder = b.childBuilder.DeepCopy().(_S7PayloadChildBuilder)
	_copy.childBuilder.setParent(_copy)
	if b.err != nil {
		_copy.err = b.err.DeepCopy().(*utils.MultiError)
	}
	return _copy
}

// CreateS7PayloadBuilder creates a S7PayloadBuilder
func (b *_S7Payload) CreateS7PayloadBuilder() S7PayloadBuilder {
	if b == nil {
		return NewS7PayloadBuilder()
	}
	return &_S7PayloadBuilder{_S7Payload: b.deepCopy()}
}

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

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

func (m *_S7Payload) GetTypeName() string {
	return "S7Payload"
}

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

	return lengthInBits
}

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

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

func S7PayloadParse[T S7Payload](ctx context.Context, theBytes []byte, messageType uint8, parameter S7Parameter) (T, error) {
	return S7PayloadParseWithBuffer[T](ctx, utils.NewReadBufferByteBased(theBytes), messageType, parameter)
}

func S7PayloadParseWithBufferProducer[T S7Payload](messageType uint8, parameter S7Parameter) func(ctx context.Context, readBuffer utils.ReadBuffer) (T, error) {
	return func(ctx context.Context, readBuffer utils.ReadBuffer) (T, error) {
		v, err := S7PayloadParseWithBuffer[T](ctx, readBuffer, messageType, parameter)
		if err != nil {
			var zero T
			return zero, err
		}
		return v, nil
	}
}

func S7PayloadParseWithBuffer[T S7Payload](ctx context.Context, readBuffer utils.ReadBuffer, messageType uint8, parameter S7Parameter) (T, error) {
	v, err := (&_S7Payload{Parameter: parameter}).parse(ctx, readBuffer, messageType, parameter)
	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 *_S7Payload) parse(ctx context.Context, readBuffer utils.ReadBuffer, messageType uint8, parameter S7Parameter) (__s7Payload S7Payload, err error) {
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("S7Payload"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for S7Payload")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

	// Switch Field (Depending on the discriminator values, passes the instantiation to a sub-type)
	var _child S7Payload
	switch {
	case CastS7Parameter(parameter).GetParameterType() == 0x04 && messageType == 0x03: // S7PayloadReadVarResponse
		if _child, err = new(_S7PayloadReadVarResponse).parse(ctx, readBuffer, m, messageType, parameter); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type S7PayloadReadVarResponse for type-switch of S7Payload")
		}
	case CastS7Parameter(parameter).GetParameterType() == 0x05 && messageType == 0x01: // S7PayloadWriteVarRequest
		if _child, err = new(_S7PayloadWriteVarRequest).parse(ctx, readBuffer, m, messageType, parameter); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type S7PayloadWriteVarRequest for type-switch of S7Payload")
		}
	case CastS7Parameter(parameter).GetParameterType() == 0x05 && messageType == 0x03: // S7PayloadWriteVarResponse
		if _child, err = new(_S7PayloadWriteVarResponse).parse(ctx, readBuffer, m, messageType, parameter); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type S7PayloadWriteVarResponse for type-switch of S7Payload")
		}
	case CastS7Parameter(parameter).GetParameterType() == 0x00 && messageType == 0x07: // S7PayloadUserData
		if _child, err = new(_S7PayloadUserData).parse(ctx, readBuffer, m, messageType, parameter); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type S7PayloadUserData for type-switch of S7Payload")
		}
	default:
		return nil, errors.Errorf("Unmapped type for parameters [parameterparameterType=%v, messageType=%v]", CastS7Parameter(parameter).GetParameterType(), messageType)
	}

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

	return _child, nil
}

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

	// 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("S7Payload"); popErr != nil {
		return errors.Wrap(popErr, "Error popping for S7Payload")
	}
	return nil
}

////
// Arguments Getter

func (m *_S7Payload) GetParameter() S7Parameter {
	return m.Parameter
}

//
////

func (m *_S7Payload) IsS7Payload() {}

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

func (m *_S7Payload) deepCopy() *_S7Payload {
	if m == nil {
		return nil
	}
	_S7PayloadCopy := &_S7Payload{
		nil, // will be set by child
		m.Parameter,
	}
	return _S7PayloadCopy
}
