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

// CALDataStatus is the corresponding interface of CALDataStatus
type CALDataStatus interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	CALData
	// GetApplication returns Application (property field)
	GetApplication() ApplicationIdContainer
	// GetBlockStart returns BlockStart (property field)
	GetBlockStart() uint8
	// GetStatusBytes returns StatusBytes (property field)
	GetStatusBytes() []StatusByte
	// IsCALDataStatus is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsCALDataStatus()
	// CreateBuilder creates a CALDataStatusBuilder
	CreateCALDataStatusBuilder() CALDataStatusBuilder
}

// _CALDataStatus is the data-structure of this message
type _CALDataStatus struct {
	CALDataContract
	Application ApplicationIdContainer
	BlockStart  uint8
	StatusBytes []StatusByte
}

var _ CALDataStatus = (*_CALDataStatus)(nil)
var _ CALDataRequirements = (*_CALDataStatus)(nil)

// NewCALDataStatus factory function for _CALDataStatus
func NewCALDataStatus(commandTypeContainer CALCommandTypeContainer, additionalData CALData, application ApplicationIdContainer, blockStart uint8, statusBytes []StatusByte, requestContext RequestContext) *_CALDataStatus {
	_result := &_CALDataStatus{
		CALDataContract: NewCALData(commandTypeContainer, additionalData, requestContext),
		Application:     application,
		BlockStart:      blockStart,
		StatusBytes:     statusBytes,
	}
	_result.CALDataContract.(*_CALData)._SubType = _result
	return _result
}

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

// CALDataStatusBuilder is a builder for CALDataStatus
type CALDataStatusBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(application ApplicationIdContainer, blockStart uint8, statusBytes []StatusByte) CALDataStatusBuilder
	// WithApplication adds Application (property field)
	WithApplication(ApplicationIdContainer) CALDataStatusBuilder
	// WithBlockStart adds BlockStart (property field)
	WithBlockStart(uint8) CALDataStatusBuilder
	// WithStatusBytes adds StatusBytes (property field)
	WithStatusBytes(...StatusByte) CALDataStatusBuilder
	// Done is used to finish work on this child and return (or create one if none) to the parent builder
	Done() CALDataBuilder
	// Build builds the CALDataStatus or returns an error if something is wrong
	Build() (CALDataStatus, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() CALDataStatus
}

// NewCALDataStatusBuilder() creates a CALDataStatusBuilder
func NewCALDataStatusBuilder() CALDataStatusBuilder {
	return &_CALDataStatusBuilder{_CALDataStatus: new(_CALDataStatus)}
}

type _CALDataStatusBuilder struct {
	*_CALDataStatus

	parentBuilder *_CALDataBuilder

	err *utils.MultiError
}

var _ (CALDataStatusBuilder) = (*_CALDataStatusBuilder)(nil)

func (b *_CALDataStatusBuilder) setParent(contract CALDataContract) {
	b.CALDataContract = contract
	contract.(*_CALData)._SubType = b._CALDataStatus
}

func (b *_CALDataStatusBuilder) WithMandatoryFields(application ApplicationIdContainer, blockStart uint8, statusBytes []StatusByte) CALDataStatusBuilder {
	return b.WithApplication(application).WithBlockStart(blockStart).WithStatusBytes(statusBytes...)
}

func (b *_CALDataStatusBuilder) WithApplication(application ApplicationIdContainer) CALDataStatusBuilder {
	b.Application = application
	return b
}

func (b *_CALDataStatusBuilder) WithBlockStart(blockStart uint8) CALDataStatusBuilder {
	b.BlockStart = blockStart
	return b
}

func (b *_CALDataStatusBuilder) WithStatusBytes(statusBytes ...StatusByte) CALDataStatusBuilder {
	b.StatusBytes = statusBytes
	return b
}

func (b *_CALDataStatusBuilder) Build() (CALDataStatus, error) {
	if b.err != nil {
		return nil, errors.Wrap(b.err, "error occurred during build")
	}
	return b._CALDataStatus.deepCopy(), nil
}

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

func (b *_CALDataStatusBuilder) Done() CALDataBuilder {
	if b.parentBuilder == nil {
		b.parentBuilder = NewCALDataBuilder().(*_CALDataBuilder)
	}
	return b.parentBuilder
}

func (b *_CALDataStatusBuilder) buildForCALData() (CALData, error) {
	return b.Build()
}

func (b *_CALDataStatusBuilder) DeepCopy() any {
	_copy := b.CreateCALDataStatusBuilder().(*_CALDataStatusBuilder)
	if b.err != nil {
		_copy.err = b.err.DeepCopy().(*utils.MultiError)
	}
	return _copy
}

// CreateCALDataStatusBuilder creates a CALDataStatusBuilder
func (b *_CALDataStatus) CreateCALDataStatusBuilder() CALDataStatusBuilder {
	if b == nil {
		return NewCALDataStatusBuilder()
	}
	return &_CALDataStatusBuilder{_CALDataStatus: b.deepCopy()}
}

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

///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/////////////////////// Accessors for discriminator values.
///////////////////////

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

func (m *_CALDataStatus) GetParent() CALDataContract {
	return m.CALDataContract
}

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

func (m *_CALDataStatus) GetApplication() ApplicationIdContainer {
	return m.Application
}

func (m *_CALDataStatus) GetBlockStart() uint8 {
	return m.BlockStart
}

func (m *_CALDataStatus) GetStatusBytes() []StatusByte {
	return m.StatusBytes
}

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

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

func (m *_CALDataStatus) GetTypeName() string {
	return "CALDataStatus"
}

func (m *_CALDataStatus) GetLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(m.CALDataContract.(*_CALData).getLengthInBits(ctx))

	// Simple field (application)
	lengthInBits += 8

	// Simple field (blockStart)
	lengthInBits += 8

	// Array field
	if len(m.StatusBytes) > 0 {
		for _curItem, element := range m.StatusBytes {
			arrayCtx := utils.CreateArrayContext(ctx, len(m.StatusBytes), _curItem)
			lengthInBits += element.GetLengthInBits(arrayCtx)
		}
	}

	return lengthInBits
}

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

func (m *_CALDataStatus) parse(ctx context.Context, readBuffer utils.ReadBuffer, parent *_CALData, commandTypeContainer CALCommandTypeContainer, requestContext RequestContext) (__cALDataStatus CALDataStatus, err error) {
	m.CALDataContract = parent
	parent._SubType = m
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("CALDataStatus"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for CALDataStatus")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

	application, err := ReadEnumField[ApplicationIdContainer](ctx, "application", "ApplicationIdContainer", ReadEnum(ApplicationIdContainerByValue, ReadUnsignedByte(readBuffer, uint8(8))))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'application' field"))
	}
	m.Application = application

	blockStart, err := ReadSimpleField(ctx, "blockStart", ReadUnsignedByte(readBuffer, uint8(8)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'blockStart' field"))
	}
	m.BlockStart = blockStart

	statusBytes, err := ReadCountArrayField[StatusByte](ctx, "statusBytes", ReadComplex[StatusByte](StatusByteParseWithBuffer, readBuffer), uint64(int32(commandTypeContainer.NumBytes())-int32(int32(2))))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'statusBytes' field"))
	}
	m.StatusBytes = statusBytes

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

	return m, nil
}

func (m *_CALDataStatus) Serialize() ([]byte, error) {
	wb := utils.NewWriteBufferByteBased(utils.WithInitialSizeForByteBasedBuffer(int(m.GetLengthInBytes(context.Background()))))
	if err := m.SerializeWithWriteBuffer(context.Background(), wb); err != nil {
		return nil, err
	}
	return wb.GetBytes(), nil
}

func (m *_CALDataStatus) SerializeWithWriteBuffer(ctx context.Context, writeBuffer utils.WriteBuffer) error {
	positionAware := writeBuffer
	_ = positionAware
	log := zerolog.Ctx(ctx)
	_ = log
	ser := func() error {
		if pushErr := writeBuffer.PushContext("CALDataStatus"); pushErr != nil {
			return errors.Wrap(pushErr, "Error pushing for CALDataStatus")
		}

		if err := WriteSimpleEnumField[ApplicationIdContainer](ctx, "application", "ApplicationIdContainer", m.GetApplication(), WriteEnum[ApplicationIdContainer, uint8](ApplicationIdContainer.GetValue, ApplicationIdContainer.PLC4XEnumName, WriteUnsignedByte(writeBuffer, 8))); err != nil {
			return errors.Wrap(err, "Error serializing 'application' field")
		}

		if err := WriteSimpleField[uint8](ctx, "blockStart", m.GetBlockStart(), WriteUnsignedByte(writeBuffer, 8)); err != nil {
			return errors.Wrap(err, "Error serializing 'blockStart' field")
		}

		if err := WriteComplexTypeArrayField(ctx, "statusBytes", m.GetStatusBytes(), writeBuffer); err != nil {
			return errors.Wrap(err, "Error serializing 'statusBytes' field")
		}

		if popErr := writeBuffer.PopContext("CALDataStatus"); popErr != nil {
			return errors.Wrap(popErr, "Error popping for CALDataStatus")
		}
		return nil
	}
	return m.CALDataContract.(*_CALData).serializeParent(ctx, writeBuffer, m, ser)
}

func (m *_CALDataStatus) IsCALDataStatus() {}

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

func (m *_CALDataStatus) deepCopy() *_CALDataStatus {
	if m == nil {
		return nil
	}
	_CALDataStatusCopy := &_CALDataStatus{
		m.CALDataContract.(*_CALData).deepCopy(),
		m.Application,
		m.BlockStart,
		utils.DeepCopySlice[StatusByte, StatusByte](m.StatusBytes),
	}
	_CALDataStatusCopy.CALDataContract.(*_CALData)._SubType = m
	return _CALDataStatusCopy
}

func (m *_CALDataStatus) String() string {
	if m == nil {
		return "<nil>"
	}
	wb := utils.NewWriteBufferBoxBased(
		utils.WithWriteBufferBoxBasedMergeSingleBoxes(),
		utils.WithWriteBufferBoxBasedOmitEmptyBoxes(),
		utils.WithWriteBufferBoxBasedPrintPosLengthFooter(),
	)
	if err := wb.WriteSerializable(context.Background(), m); err != nil {
		return err.Error()
	}
	return wb.GetBox().String()
}
