/*
 * 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"
	"encoding/binary"
	stdErrors "errors"
	"fmt"

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

	"github.com/apache/plc4x/plc4go/spi/codegen"
	. "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.

// FirmataMessage is the corresponding interface of FirmataMessage
type FirmataMessage interface {
	FirmataMessageContract
	FirmataMessageRequirements
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	// IsFirmataMessage is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsFirmataMessage()
	// CreateBuilder creates a FirmataMessageBuilder
	CreateFirmataMessageBuilder() FirmataMessageBuilder
}

// FirmataMessageContract provides a set of functions which can be overwritten by a sub struct
type FirmataMessageContract interface {
	// IsFirmataMessage is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsFirmataMessage()
	// CreateBuilder creates a FirmataMessageBuilder
	CreateFirmataMessageBuilder() FirmataMessageBuilder
}

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

// _FirmataMessage is the data-structure of this message
type _FirmataMessage struct {
	_SubType interface {
		FirmataMessageContract
		FirmataMessageRequirements
	}
}

var _ FirmataMessageContract = (*_FirmataMessage)(nil)

// NewFirmataMessage factory function for _FirmataMessage
func NewFirmataMessage() *_FirmataMessage {
	return &_FirmataMessage{}
}

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

// FirmataMessageBuilder is a builder for FirmataMessage
type FirmataMessageBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields() FirmataMessageBuilder
	// AsFirmataMessageAnalogIO converts this build to a subType of FirmataMessage. It is always possible to return to current builder using Done()
	AsFirmataMessageAnalogIO() FirmataMessageAnalogIOBuilder
	// AsFirmataMessageDigitalIO converts this build to a subType of FirmataMessage. It is always possible to return to current builder using Done()
	AsFirmataMessageDigitalIO() FirmataMessageDigitalIOBuilder
	// AsFirmataMessageSubscribeAnalogPinValue converts this build to a subType of FirmataMessage. It is always possible to return to current builder using Done()
	AsFirmataMessageSubscribeAnalogPinValue() FirmataMessageSubscribeAnalogPinValueBuilder
	// AsFirmataMessageSubscribeDigitalPinValue converts this build to a subType of FirmataMessage. It is always possible to return to current builder using Done()
	AsFirmataMessageSubscribeDigitalPinValue() FirmataMessageSubscribeDigitalPinValueBuilder
	// AsFirmataMessageCommand converts this build to a subType of FirmataMessage. It is always possible to return to current builder using Done()
	AsFirmataMessageCommand() FirmataMessageCommandBuilder
	// Build builds the FirmataMessage or returns an error if something is wrong
	PartialBuild() (FirmataMessageContract, error)
	// MustBuild does the same as Build but panics on error
	PartialMustBuild() FirmataMessageContract
	// Build builds the FirmataMessage or returns an error if something is wrong
	Build() (FirmataMessage, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() FirmataMessage
}

// NewFirmataMessageBuilder() creates a FirmataMessageBuilder
func NewFirmataMessageBuilder() FirmataMessageBuilder {
	return &_FirmataMessageBuilder{_FirmataMessage: new(_FirmataMessage)}
}

type _FirmataMessageChildBuilder interface {
	utils.Copyable
	setParent(FirmataMessageContract)
	buildForFirmataMessage() (FirmataMessage, error)
}

type _FirmataMessageBuilder struct {
	*_FirmataMessage

	childBuilder _FirmataMessageChildBuilder

	collectedErr []error
}

var _ (FirmataMessageBuilder) = (*_FirmataMessageBuilder)(nil)

func (b *_FirmataMessageBuilder) WithMandatoryFields() FirmataMessageBuilder {
	return b
}

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

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

func (b *_FirmataMessageBuilder) AsFirmataMessageAnalogIO() FirmataMessageAnalogIOBuilder {
	if cb, ok := b.childBuilder.(FirmataMessageAnalogIOBuilder); ok {
		return cb
	}
	cb := NewFirmataMessageAnalogIOBuilder().(*_FirmataMessageAnalogIOBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_FirmataMessageBuilder) AsFirmataMessageDigitalIO() FirmataMessageDigitalIOBuilder {
	if cb, ok := b.childBuilder.(FirmataMessageDigitalIOBuilder); ok {
		return cb
	}
	cb := NewFirmataMessageDigitalIOBuilder().(*_FirmataMessageDigitalIOBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_FirmataMessageBuilder) AsFirmataMessageSubscribeAnalogPinValue() FirmataMessageSubscribeAnalogPinValueBuilder {
	if cb, ok := b.childBuilder.(FirmataMessageSubscribeAnalogPinValueBuilder); ok {
		return cb
	}
	cb := NewFirmataMessageSubscribeAnalogPinValueBuilder().(*_FirmataMessageSubscribeAnalogPinValueBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_FirmataMessageBuilder) AsFirmataMessageSubscribeDigitalPinValue() FirmataMessageSubscribeDigitalPinValueBuilder {
	if cb, ok := b.childBuilder.(FirmataMessageSubscribeDigitalPinValueBuilder); ok {
		return cb
	}
	cb := NewFirmataMessageSubscribeDigitalPinValueBuilder().(*_FirmataMessageSubscribeDigitalPinValueBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_FirmataMessageBuilder) AsFirmataMessageCommand() FirmataMessageCommandBuilder {
	if cb, ok := b.childBuilder.(FirmataMessageCommandBuilder); ok {
		return cb
	}
	cb := NewFirmataMessageCommandBuilder().(*_FirmataMessageCommandBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_FirmataMessageBuilder) Build() (FirmataMessage, 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.buildForFirmataMessage()
}

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

func (b *_FirmataMessageBuilder) DeepCopy() any {
	_copy := b.CreateFirmataMessageBuilder().(*_FirmataMessageBuilder)
	_copy.childBuilder = b.childBuilder.DeepCopy().(_FirmataMessageChildBuilder)
	_copy.childBuilder.setParent(_copy)
	if b.collectedErr != nil {
		copy(_copy.collectedErr, b.collectedErr)
	}
	return _copy
}

// CreateFirmataMessageBuilder creates a FirmataMessageBuilder
func (b *_FirmataMessage) CreateFirmataMessageBuilder() FirmataMessageBuilder {
	if b == nil {
		return NewFirmataMessageBuilder()
	}
	return &_FirmataMessageBuilder{_FirmataMessage: b.deepCopy()}
}

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

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

func (m *_FirmataMessage) GetTypeName() string {
	return "FirmataMessage"
}

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

	return lengthInBits
}

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

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

func FirmataMessageParse[T FirmataMessage](ctx context.Context, theBytes []byte, response bool) (T, error) {
	return FirmataMessageParseWithBuffer[T](ctx, utils.NewReadBufferByteBased(theBytes, utils.WithByteOrderForReadBufferByteBased(binary.BigEndian)), response)
}

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

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

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

	// Switch Field (Depending on the discriminator values, passes the instantiation to a sub-type)
	var _child FirmataMessage
	switch {
	case messageType == 0xE: // FirmataMessageAnalogIO
		if _child, err = new(_FirmataMessageAnalogIO).parse(ctx, readBuffer, m, response); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type FirmataMessageAnalogIO for type-switch of FirmataMessage")
		}
	case messageType == 0x9: // FirmataMessageDigitalIO
		if _child, err = new(_FirmataMessageDigitalIO).parse(ctx, readBuffer, m, response); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type FirmataMessageDigitalIO for type-switch of FirmataMessage")
		}
	case messageType == 0xC: // FirmataMessageSubscribeAnalogPinValue
		if _child, err = new(_FirmataMessageSubscribeAnalogPinValue).parse(ctx, readBuffer, m, response); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type FirmataMessageSubscribeAnalogPinValue for type-switch of FirmataMessage")
		}
	case messageType == 0xD: // FirmataMessageSubscribeDigitalPinValue
		if _child, err = new(_FirmataMessageSubscribeDigitalPinValue).parse(ctx, readBuffer, m, response); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type FirmataMessageSubscribeDigitalPinValue for type-switch of FirmataMessage")
		}
	case messageType == 0xF: // FirmataMessageCommand
		if _child, err = new(_FirmataMessageCommand).parse(ctx, readBuffer, m, response); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type FirmataMessageCommand for type-switch of FirmataMessage")
		}
	default:
		return nil, errors.Errorf("Unmapped type for parameters [messageType=%v]", messageType)
	}

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

	return _child, nil
}

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

	if err := WriteDiscriminatorField(ctx, "messageType", m.GetMessageType(), WriteUnsignedByte(writeBuffer, 4), codegen.WithByteOrder(binary.BigEndian)); err != nil {
		return errors.Wrap(err, "Error serializing 'messageType' 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("FirmataMessage"); popErr != nil {
		return errors.Wrap(popErr, "Error popping for FirmataMessage")
	}
	return nil
}

func (m *_FirmataMessage) IsFirmataMessage() {}

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

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