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

// ReadAtTimeDetails is the corresponding interface of ReadAtTimeDetails
type ReadAtTimeDetails interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetReqTimes returns ReqTimes (property field)
	GetReqTimes() []int64
	// GetUseSimpleBounds returns UseSimpleBounds (property field)
	GetUseSimpleBounds() bool
	// IsReadAtTimeDetails is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsReadAtTimeDetails()
	// CreateBuilder creates a ReadAtTimeDetailsBuilder
	CreateReadAtTimeDetailsBuilder() ReadAtTimeDetailsBuilder
}

// _ReadAtTimeDetails is the data-structure of this message
type _ReadAtTimeDetails struct {
	ExtensionObjectDefinitionContract
	ReqTimes        []int64
	UseSimpleBounds bool
	// Reserved Fields
	reservedField0 *uint8
}

var _ ReadAtTimeDetails = (*_ReadAtTimeDetails)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_ReadAtTimeDetails)(nil)

// NewReadAtTimeDetails factory function for _ReadAtTimeDetails
func NewReadAtTimeDetails(reqTimes []int64, useSimpleBounds bool) *_ReadAtTimeDetails {
	_result := &_ReadAtTimeDetails{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		ReqTimes:                          reqTimes,
		UseSimpleBounds:                   useSimpleBounds,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// ReadAtTimeDetailsBuilder is a builder for ReadAtTimeDetails
type ReadAtTimeDetailsBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(reqTimes []int64, useSimpleBounds bool) ReadAtTimeDetailsBuilder
	// WithReqTimes adds ReqTimes (property field)
	WithReqTimes(...int64) ReadAtTimeDetailsBuilder
	// WithUseSimpleBounds adds UseSimpleBounds (property field)
	WithUseSimpleBounds(bool) ReadAtTimeDetailsBuilder
	// Done is used to finish work on this child and return (or create one if none) to the parent builder
	Done() ExtensionObjectDefinitionBuilder
	// Build builds the ReadAtTimeDetails or returns an error if something is wrong
	Build() (ReadAtTimeDetails, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() ReadAtTimeDetails
}

// NewReadAtTimeDetailsBuilder() creates a ReadAtTimeDetailsBuilder
func NewReadAtTimeDetailsBuilder() ReadAtTimeDetailsBuilder {
	return &_ReadAtTimeDetailsBuilder{_ReadAtTimeDetails: new(_ReadAtTimeDetails)}
}

type _ReadAtTimeDetailsBuilder struct {
	*_ReadAtTimeDetails

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (ReadAtTimeDetailsBuilder) = (*_ReadAtTimeDetailsBuilder)(nil)

func (b *_ReadAtTimeDetailsBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._ReadAtTimeDetails
}

func (b *_ReadAtTimeDetailsBuilder) WithMandatoryFields(reqTimes []int64, useSimpleBounds bool) ReadAtTimeDetailsBuilder {
	return b.WithReqTimes(reqTimes...).WithUseSimpleBounds(useSimpleBounds)
}

func (b *_ReadAtTimeDetailsBuilder) WithReqTimes(reqTimes ...int64) ReadAtTimeDetailsBuilder {
	b.ReqTimes = reqTimes
	return b
}

func (b *_ReadAtTimeDetailsBuilder) WithUseSimpleBounds(useSimpleBounds bool) ReadAtTimeDetailsBuilder {
	b.UseSimpleBounds = useSimpleBounds
	return b
}

func (b *_ReadAtTimeDetailsBuilder) Build() (ReadAtTimeDetails, error) {
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._ReadAtTimeDetails.deepCopy(), nil
}

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

func (b *_ReadAtTimeDetailsBuilder) Done() ExtensionObjectDefinitionBuilder {
	if b.parentBuilder == nil {
		b.parentBuilder = NewExtensionObjectDefinitionBuilder().(*_ExtensionObjectDefinitionBuilder)
	}
	return b.parentBuilder
}

func (b *_ReadAtTimeDetailsBuilder) buildForExtensionObjectDefinition() (ExtensionObjectDefinition, error) {
	return b.Build()
}

func (b *_ReadAtTimeDetailsBuilder) DeepCopy() any {
	_copy := b.CreateReadAtTimeDetailsBuilder().(*_ReadAtTimeDetailsBuilder)
	if b.collectedErr != nil {
		copy(_copy.collectedErr, b.collectedErr)
	}
	return _copy
}

// CreateReadAtTimeDetailsBuilder creates a ReadAtTimeDetailsBuilder
func (b *_ReadAtTimeDetails) CreateReadAtTimeDetailsBuilder() ReadAtTimeDetailsBuilder {
	if b == nil {
		return NewReadAtTimeDetailsBuilder()
	}
	return &_ReadAtTimeDetailsBuilder{_ReadAtTimeDetails: b.deepCopy()}
}

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

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

func (m *_ReadAtTimeDetails) GetExtensionId() int32 {
	return int32(655)
}

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

func (m *_ReadAtTimeDetails) GetParent() ExtensionObjectDefinitionContract {
	return m.ExtensionObjectDefinitionContract
}

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

func (m *_ReadAtTimeDetails) GetReqTimes() []int64 {
	return m.ReqTimes
}

func (m *_ReadAtTimeDetails) GetUseSimpleBounds() bool {
	return m.UseSimpleBounds
}

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

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

func (m *_ReadAtTimeDetails) GetTypeName() string {
	return "ReadAtTimeDetails"
}

func (m *_ReadAtTimeDetails) GetLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).getLengthInBits(ctx))

	// Implicit Field (noOfReqTimes)
	lengthInBits += 32

	// Array field
	if len(m.ReqTimes) > 0 {
		lengthInBits += 64 * uint16(len(m.ReqTimes))
	}

	// Reserved Field (reserved)
	lengthInBits += 7

	// Simple field (useSimpleBounds)
	lengthInBits += 1

	return lengthInBits
}

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

func (m *_ReadAtTimeDetails) parse(ctx context.Context, readBuffer utils.ReadBuffer, parent *_ExtensionObjectDefinition, extensionId int32) (__readAtTimeDetails ReadAtTimeDetails, err error) {
	m.ExtensionObjectDefinitionContract = parent
	parent._SubType = m
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("ReadAtTimeDetails"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for ReadAtTimeDetails")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

	noOfReqTimes, err := ReadImplicitField[int32](ctx, "noOfReqTimes", ReadSignedInt(readBuffer, uint8(32)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'noOfReqTimes' field"))
	}
	_ = noOfReqTimes

	reqTimes, err := ReadCountArrayField[int64](ctx, "reqTimes", ReadSignedLong(readBuffer, uint8(64)), uint64(noOfReqTimes))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'reqTimes' field"))
	}
	m.ReqTimes = reqTimes

	reservedField0, err := ReadReservedField(ctx, "reserved", ReadUnsignedByte(readBuffer, uint8(7)), uint8(0x00))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing reserved field"))
	}
	m.reservedField0 = reservedField0

	useSimpleBounds, err := ReadSimpleField(ctx, "useSimpleBounds", ReadBoolean(readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'useSimpleBounds' field"))
	}
	m.UseSimpleBounds = useSimpleBounds

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

	return m, nil
}

func (m *_ReadAtTimeDetails) 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 *_ReadAtTimeDetails) SerializeWithWriteBuffer(ctx context.Context, writeBuffer utils.WriteBuffer) error {
	positionAware := writeBuffer
	_ = positionAware
	log := zerolog.Ctx(ctx)
	_ = log
	ser := func() error {
		if pushErr := writeBuffer.PushContext("ReadAtTimeDetails"); pushErr != nil {
			return errors.Wrap(pushErr, "Error pushing for ReadAtTimeDetails")
		}
		noOfReqTimes := int32(utils.InlineIf(bool((m.GetReqTimes()) == (nil)), func() any { return int32(-(int32(1))) }, func() any { return int32(int32(len(m.GetReqTimes()))) }).(int32))
		if err := WriteImplicitField(ctx, "noOfReqTimes", noOfReqTimes, WriteSignedInt(writeBuffer, 32)); err != nil {
			return errors.Wrap(err, "Error serializing 'noOfReqTimes' field")
		}

		if err := WriteSimpleTypeArrayField(ctx, "reqTimes", m.GetReqTimes(), WriteSignedLong(writeBuffer, 64)); err != nil {
			return errors.Wrap(err, "Error serializing 'reqTimes' field")
		}

		if err := WriteReservedField[uint8](ctx, "reserved", uint8(0x00), WriteUnsignedByte(writeBuffer, 7)); err != nil {
			return errors.Wrap(err, "Error serializing 'reserved' field number 1")
		}

		if err := WriteSimpleField[bool](ctx, "useSimpleBounds", m.GetUseSimpleBounds(), WriteBoolean(writeBuffer)); err != nil {
			return errors.Wrap(err, "Error serializing 'useSimpleBounds' field")
		}

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

func (m *_ReadAtTimeDetails) IsReadAtTimeDetails() {}

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

func (m *_ReadAtTimeDetails) deepCopy() *_ReadAtTimeDetails {
	if m == nil {
		return nil
	}
	_ReadAtTimeDetailsCopy := &_ReadAtTimeDetails{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopySlice[int64, int64](m.ReqTimes),
		m.UseSimpleBounds,
		m.reservedField0,
	}
	_ReadAtTimeDetailsCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _ReadAtTimeDetailsCopy
}

func (m *_ReadAtTimeDetails) 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()
}
