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

// FirmataCommand is the corresponding interface of FirmataCommand
type FirmataCommand interface {
	FirmataCommandContract
	FirmataCommandRequirements
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	// IsFirmataCommand is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsFirmataCommand()
	// CreateBuilder creates a FirmataCommandBuilder
	CreateFirmataCommandBuilder() FirmataCommandBuilder
}

// FirmataCommandContract provides a set of functions which can be overwritten by a sub struct
type FirmataCommandContract interface {
	// IsFirmataCommand is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsFirmataCommand()
	// CreateBuilder creates a FirmataCommandBuilder
	CreateFirmataCommandBuilder() FirmataCommandBuilder
}

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

// _FirmataCommand is the data-structure of this message
type _FirmataCommand struct {
	_SubType interface {
		FirmataCommandContract
		FirmataCommandRequirements
	}
}

var _ FirmataCommandContract = (*_FirmataCommand)(nil)

// NewFirmataCommand factory function for _FirmataCommand
func NewFirmataCommand() *_FirmataCommand {
	return &_FirmataCommand{}
}

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

// FirmataCommandBuilder is a builder for FirmataCommand
type FirmataCommandBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields() FirmataCommandBuilder
	// AsFirmataCommandSysex converts this build to a subType of FirmataCommand. It is always possible to return to current builder using Done()
	AsFirmataCommandSysex() FirmataCommandSysexBuilder
	// AsFirmataCommandSetPinMode converts this build to a subType of FirmataCommand. It is always possible to return to current builder using Done()
	AsFirmataCommandSetPinMode() FirmataCommandSetPinModeBuilder
	// AsFirmataCommandSetDigitalPinValue converts this build to a subType of FirmataCommand. It is always possible to return to current builder using Done()
	AsFirmataCommandSetDigitalPinValue() FirmataCommandSetDigitalPinValueBuilder
	// AsFirmataCommandProtocolVersion converts this build to a subType of FirmataCommand. It is always possible to return to current builder using Done()
	AsFirmataCommandProtocolVersion() FirmataCommandProtocolVersionBuilder
	// AsFirmataCommandSystemReset converts this build to a subType of FirmataCommand. It is always possible to return to current builder using Done()
	AsFirmataCommandSystemReset() FirmataCommandSystemResetBuilder
	// Build builds the FirmataCommand or returns an error if something is wrong
	PartialBuild() (FirmataCommandContract, error)
	// MustBuild does the same as Build but panics on error
	PartialMustBuild() FirmataCommandContract
	// Build builds the FirmataCommand or returns an error if something is wrong
	Build() (FirmataCommand, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() FirmataCommand
}

// NewFirmataCommandBuilder() creates a FirmataCommandBuilder
func NewFirmataCommandBuilder() FirmataCommandBuilder {
	return &_FirmataCommandBuilder{_FirmataCommand: new(_FirmataCommand)}
}

type _FirmataCommandChildBuilder interface {
	utils.Copyable
	setParent(FirmataCommandContract)
	buildForFirmataCommand() (FirmataCommand, error)
}

type _FirmataCommandBuilder struct {
	*_FirmataCommand

	childBuilder _FirmataCommandChildBuilder

	collectedErr []error
}

var _ (FirmataCommandBuilder) = (*_FirmataCommandBuilder)(nil)

func (b *_FirmataCommandBuilder) WithMandatoryFields() FirmataCommandBuilder {
	return b
}

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

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

func (b *_FirmataCommandBuilder) AsFirmataCommandSysex() FirmataCommandSysexBuilder {
	if cb, ok := b.childBuilder.(FirmataCommandSysexBuilder); ok {
		return cb
	}
	cb := NewFirmataCommandSysexBuilder().(*_FirmataCommandSysexBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_FirmataCommandBuilder) AsFirmataCommandSetPinMode() FirmataCommandSetPinModeBuilder {
	if cb, ok := b.childBuilder.(FirmataCommandSetPinModeBuilder); ok {
		return cb
	}
	cb := NewFirmataCommandSetPinModeBuilder().(*_FirmataCommandSetPinModeBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_FirmataCommandBuilder) AsFirmataCommandSetDigitalPinValue() FirmataCommandSetDigitalPinValueBuilder {
	if cb, ok := b.childBuilder.(FirmataCommandSetDigitalPinValueBuilder); ok {
		return cb
	}
	cb := NewFirmataCommandSetDigitalPinValueBuilder().(*_FirmataCommandSetDigitalPinValueBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_FirmataCommandBuilder) AsFirmataCommandProtocolVersion() FirmataCommandProtocolVersionBuilder {
	if cb, ok := b.childBuilder.(FirmataCommandProtocolVersionBuilder); ok {
		return cb
	}
	cb := NewFirmataCommandProtocolVersionBuilder().(*_FirmataCommandProtocolVersionBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_FirmataCommandBuilder) AsFirmataCommandSystemReset() FirmataCommandSystemResetBuilder {
	if cb, ok := b.childBuilder.(FirmataCommandSystemResetBuilder); ok {
		return cb
	}
	cb := NewFirmataCommandSystemResetBuilder().(*_FirmataCommandSystemResetBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_FirmataCommandBuilder) Build() (FirmataCommand, 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.buildForFirmataCommand()
}

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

func (b *_FirmataCommandBuilder) DeepCopy() any {
	_copy := b.CreateFirmataCommandBuilder().(*_FirmataCommandBuilder)
	_copy.childBuilder = b.childBuilder.DeepCopy().(_FirmataCommandChildBuilder)
	_copy.childBuilder.setParent(_copy)
	if b.collectedErr != nil {
		copy(_copy.collectedErr, b.collectedErr)
	}
	return _copy
}

// CreateFirmataCommandBuilder creates a FirmataCommandBuilder
func (b *_FirmataCommand) CreateFirmataCommandBuilder() FirmataCommandBuilder {
	if b == nil {
		return NewFirmataCommandBuilder()
	}
	return &_FirmataCommandBuilder{_FirmataCommand: b.deepCopy()}
}

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

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

func (m *_FirmataCommand) GetTypeName() string {
	return "FirmataCommand"
}

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

	return lengthInBits
}

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

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

func FirmataCommandParse[T FirmataCommand](ctx context.Context, theBytes []byte, response bool) (T, error) {
	return FirmataCommandParseWithBuffer[T](ctx, utils.NewReadBufferByteBased(theBytes), response)
}

func FirmataCommandParseWithBufferProducer[T FirmataCommand](response bool) func(ctx context.Context, readBuffer utils.ReadBuffer) (T, error) {
	return func(ctx context.Context, readBuffer utils.ReadBuffer) (T, error) {
		v, err := FirmataCommandParseWithBuffer[T](ctx, readBuffer, response)
		if err != nil {
			var zero T
			return zero, err
		}
		return v, nil
	}
}

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

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

	// Switch Field (Depending on the discriminator values, passes the instantiation to a sub-type)
	var _child FirmataCommand
	switch {
	case commandCode == 0x0: // FirmataCommandSysex
		if _child, err = new(_FirmataCommandSysex).parse(ctx, readBuffer, m, response); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type FirmataCommandSysex for type-switch of FirmataCommand")
		}
	case commandCode == 0x4: // FirmataCommandSetPinMode
		if _child, err = new(_FirmataCommandSetPinMode).parse(ctx, readBuffer, m, response); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type FirmataCommandSetPinMode for type-switch of FirmataCommand")
		}
	case commandCode == 0x5: // FirmataCommandSetDigitalPinValue
		if _child, err = new(_FirmataCommandSetDigitalPinValue).parse(ctx, readBuffer, m, response); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type FirmataCommandSetDigitalPinValue for type-switch of FirmataCommand")
		}
	case commandCode == 0x9: // FirmataCommandProtocolVersion
		if _child, err = new(_FirmataCommandProtocolVersion).parse(ctx, readBuffer, m, response); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type FirmataCommandProtocolVersion for type-switch of FirmataCommand")
		}
	case commandCode == 0xF: // FirmataCommandSystemReset
		if _child, err = new(_FirmataCommandSystemReset).parse(ctx, readBuffer, m, response); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type FirmataCommandSystemReset for type-switch of FirmataCommand")
		}
	default:
		return nil, errors.Errorf("Unmapped type for parameters [commandCode=%v]", commandCode)
	}

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

	return _child, nil
}

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

	if err := WriteDiscriminatorField(ctx, "commandCode", m.GetCommandCode(), WriteUnsignedByte(writeBuffer, 4)); err != nil {
		return errors.Wrap(err, "Error serializing 'commandCode' 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("FirmataCommand"); popErr != nil {
		return errors.Wrap(popErr, "Error popping for FirmataCommand")
	}
	return nil
}

func (m *_FirmataCommand) IsFirmataCommand() {}

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

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