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

// MultipleServiceResponse is the corresponding interface of MultipleServiceResponse
type MultipleServiceResponse interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	CipService
	// GetStatus returns Status (property field)
	GetStatus() uint8
	// GetExtStatus returns ExtStatus (property field)
	GetExtStatus() uint8
	// GetServiceNb returns ServiceNb (property field)
	GetServiceNb() uint16
	// GetOffsets returns Offsets (property field)
	GetOffsets() []uint16
	// GetServicesData returns ServicesData (property field)
	GetServicesData() []byte
	// IsMultipleServiceResponse is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsMultipleServiceResponse()
	// CreateBuilder creates a MultipleServiceResponseBuilder
	CreateMultipleServiceResponseBuilder() MultipleServiceResponseBuilder
}

// _MultipleServiceResponse is the data-structure of this message
type _MultipleServiceResponse struct {
	CipServiceContract
	Status       uint8
	ExtStatus    uint8
	ServiceNb    uint16
	Offsets      []uint16
	ServicesData []byte
	// Reserved Fields
	reservedField0 *uint8
}

var _ MultipleServiceResponse = (*_MultipleServiceResponse)(nil)
var _ CipServiceRequirements = (*_MultipleServiceResponse)(nil)

// NewMultipleServiceResponse factory function for _MultipleServiceResponse
func NewMultipleServiceResponse(status uint8, extStatus uint8, serviceNb uint16, offsets []uint16, servicesData []byte) *_MultipleServiceResponse {
	_result := &_MultipleServiceResponse{
		CipServiceContract: NewCipService(),
		Status:             status,
		ExtStatus:          extStatus,
		ServiceNb:          serviceNb,
		Offsets:            offsets,
		ServicesData:       servicesData,
	}
	_result.CipServiceContract.(*_CipService)._SubType = _result
	return _result
}

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

// MultipleServiceResponseBuilder is a builder for MultipleServiceResponse
type MultipleServiceResponseBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(status uint8, extStatus uint8, serviceNb uint16, offsets []uint16, servicesData []byte) MultipleServiceResponseBuilder
	// WithStatus adds Status (property field)
	WithStatus(uint8) MultipleServiceResponseBuilder
	// WithExtStatus adds ExtStatus (property field)
	WithExtStatus(uint8) MultipleServiceResponseBuilder
	// WithServiceNb adds ServiceNb (property field)
	WithServiceNb(uint16) MultipleServiceResponseBuilder
	// WithOffsets adds Offsets (property field)
	WithOffsets(...uint16) MultipleServiceResponseBuilder
	// WithServicesData adds ServicesData (property field)
	WithServicesData(...byte) MultipleServiceResponseBuilder
	// Done is used to finish work on this child and return (or create one if none) to the parent builder
	Done() CipServiceBuilder
	// Build builds the MultipleServiceResponse or returns an error if something is wrong
	Build() (MultipleServiceResponse, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() MultipleServiceResponse
}

// NewMultipleServiceResponseBuilder() creates a MultipleServiceResponseBuilder
func NewMultipleServiceResponseBuilder() MultipleServiceResponseBuilder {
	return &_MultipleServiceResponseBuilder{_MultipleServiceResponse: new(_MultipleServiceResponse)}
}

type _MultipleServiceResponseBuilder struct {
	*_MultipleServiceResponse

	parentBuilder *_CipServiceBuilder

	collectedErr []error
}

var _ (MultipleServiceResponseBuilder) = (*_MultipleServiceResponseBuilder)(nil)

func (b *_MultipleServiceResponseBuilder) setParent(contract CipServiceContract) {
	b.CipServiceContract = contract
	contract.(*_CipService)._SubType = b._MultipleServiceResponse
}

func (b *_MultipleServiceResponseBuilder) WithMandatoryFields(status uint8, extStatus uint8, serviceNb uint16, offsets []uint16, servicesData []byte) MultipleServiceResponseBuilder {
	return b.WithStatus(status).WithExtStatus(extStatus).WithServiceNb(serviceNb).WithOffsets(offsets...).WithServicesData(servicesData...)
}

func (b *_MultipleServiceResponseBuilder) WithStatus(status uint8) MultipleServiceResponseBuilder {
	b.Status = status
	return b
}

func (b *_MultipleServiceResponseBuilder) WithExtStatus(extStatus uint8) MultipleServiceResponseBuilder {
	b.ExtStatus = extStatus
	return b
}

func (b *_MultipleServiceResponseBuilder) WithServiceNb(serviceNb uint16) MultipleServiceResponseBuilder {
	b.ServiceNb = serviceNb
	return b
}

func (b *_MultipleServiceResponseBuilder) WithOffsets(offsets ...uint16) MultipleServiceResponseBuilder {
	b.Offsets = offsets
	return b
}

func (b *_MultipleServiceResponseBuilder) WithServicesData(servicesData ...byte) MultipleServiceResponseBuilder {
	b.ServicesData = servicesData
	return b
}

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

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

func (b *_MultipleServiceResponseBuilder) Done() CipServiceBuilder {
	if b.parentBuilder == nil {
		b.parentBuilder = NewCipServiceBuilder().(*_CipServiceBuilder)
	}
	return b.parentBuilder
}

func (b *_MultipleServiceResponseBuilder) buildForCipService() (CipService, error) {
	return b.Build()
}

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

// CreateMultipleServiceResponseBuilder creates a MultipleServiceResponseBuilder
func (b *_MultipleServiceResponse) CreateMultipleServiceResponseBuilder() MultipleServiceResponseBuilder {
	if b == nil {
		return NewMultipleServiceResponseBuilder()
	}
	return &_MultipleServiceResponseBuilder{_MultipleServiceResponse: b.deepCopy()}
}

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

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

func (m *_MultipleServiceResponse) GetService() uint8 {
	return 0x0A
}

func (m *_MultipleServiceResponse) GetResponse() bool {
	return bool(true)
}

func (m *_MultipleServiceResponse) GetConnected() bool {
	return false
}

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

func (m *_MultipleServiceResponse) GetParent() CipServiceContract {
	return m.CipServiceContract
}

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

func (m *_MultipleServiceResponse) GetStatus() uint8 {
	return m.Status
}

func (m *_MultipleServiceResponse) GetExtStatus() uint8 {
	return m.ExtStatus
}

func (m *_MultipleServiceResponse) GetServiceNb() uint16 {
	return m.ServiceNb
}

func (m *_MultipleServiceResponse) GetOffsets() []uint16 {
	return m.Offsets
}

func (m *_MultipleServiceResponse) GetServicesData() []byte {
	return m.ServicesData
}

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

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

func (m *_MultipleServiceResponse) GetTypeName() string {
	return "MultipleServiceResponse"
}

func (m *_MultipleServiceResponse) GetLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(m.CipServiceContract.(*_CipService).getLengthInBits(ctx))

	// Reserved Field (reserved)
	lengthInBits += 8

	// Simple field (status)
	lengthInBits += 8

	// Simple field (extStatus)
	lengthInBits += 8

	// Simple field (serviceNb)
	lengthInBits += 16

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

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

	return lengthInBits
}

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

func (m *_MultipleServiceResponse) parse(ctx context.Context, readBuffer utils.ReadBuffer, parent *_CipService, connected bool, serviceLen uint16) (__multipleServiceResponse MultipleServiceResponse, err error) {
	m.CipServiceContract = parent
	parent._SubType = m
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("MultipleServiceResponse"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for MultipleServiceResponse")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

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

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

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

	serviceNb, err := ReadSimpleField(ctx, "serviceNb", ReadUnsignedShort(readBuffer, uint8(16)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'serviceNb' field"))
	}
	m.ServiceNb = serviceNb

	offsets, err := ReadCountArrayField[uint16](ctx, "offsets", ReadUnsignedShort(readBuffer, uint8(16)), uint64(serviceNb))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'offsets' field"))
	}
	m.Offsets = offsets

	servicesData, err := readBuffer.ReadByteArray("servicesData", int(int32(int32(serviceLen)-int32(int32(6)))-int32((int32(int32(2))*int32(serviceNb)))))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'servicesData' field"))
	}
	m.ServicesData = servicesData

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

	return m, nil
}

func (m *_MultipleServiceResponse) 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 *_MultipleServiceResponse) SerializeWithWriteBuffer(ctx context.Context, writeBuffer utils.WriteBuffer) error {
	positionAware := writeBuffer
	_ = positionAware
	log := zerolog.Ctx(ctx)
	_ = log
	ser := func() error {
		if pushErr := writeBuffer.PushContext("MultipleServiceResponse"); pushErr != nil {
			return errors.Wrap(pushErr, "Error pushing for MultipleServiceResponse")
		}

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

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

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

		if err := WriteSimpleField[uint16](ctx, "serviceNb", m.GetServiceNb(), WriteUnsignedShort(writeBuffer, 16)); err != nil {
			return errors.Wrap(err, "Error serializing 'serviceNb' field")
		}

		if err := WriteSimpleTypeArrayField(ctx, "offsets", m.GetOffsets(), WriteUnsignedShort(writeBuffer, 16)); err != nil {
			return errors.Wrap(err, "Error serializing 'offsets' field")
		}

		if err := WriteByteArrayField(ctx, "servicesData", m.GetServicesData(), WriteByteArray(writeBuffer, 8)); err != nil {
			return errors.Wrap(err, "Error serializing 'servicesData' field")
		}

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

func (m *_MultipleServiceResponse) IsMultipleServiceResponse() {}

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

func (m *_MultipleServiceResponse) deepCopy() *_MultipleServiceResponse {
	if m == nil {
		return nil
	}
	_MultipleServiceResponseCopy := &_MultipleServiceResponse{
		m.CipServiceContract.(*_CipService).deepCopy(),
		m.Status,
		m.ExtStatus,
		m.ServiceNb,
		utils.DeepCopySlice[uint16, uint16](m.Offsets),
		utils.DeepCopySlice[byte, byte](m.ServicesData),
		m.reservedField0,
	}
	_MultipleServiceResponseCopy.CipServiceContract.(*_CipService)._SubType = m
	return _MultipleServiceResponseCopy
}

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