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

// ServicesResponse is the corresponding interface of ServicesResponse
type ServicesResponse interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	TypeId
	// GetEncapsulationProtocol returns EncapsulationProtocol (property field)
	GetEncapsulationProtocol() uint16
	// GetSupportsCIPEncapsulation returns SupportsCIPEncapsulation (property field)
	GetSupportsCIPEncapsulation() bool
	// GetSupportsUDP returns SupportsUDP (property field)
	GetSupportsUDP() bool
	// GetData returns Data (property field)
	GetData() []byte
	// IsServicesResponse is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsServicesResponse()
	// CreateBuilder creates a ServicesResponseBuilder
	CreateServicesResponseBuilder() ServicesResponseBuilder
}

// _ServicesResponse is the data-structure of this message
type _ServicesResponse struct {
	TypeIdContract
	EncapsulationProtocol    uint16
	SupportsCIPEncapsulation bool
	SupportsUDP              bool
	Data                     []byte
	// Reserved Fields
	reservedField0 *uint8
	reservedField1 *uint16
}

var _ ServicesResponse = (*_ServicesResponse)(nil)
var _ TypeIdRequirements = (*_ServicesResponse)(nil)

// NewServicesResponse factory function for _ServicesResponse
func NewServicesResponse(encapsulationProtocol uint16, supportsCIPEncapsulation bool, supportsUDP bool, data []byte) *_ServicesResponse {
	_result := &_ServicesResponse{
		TypeIdContract:           NewTypeId(),
		EncapsulationProtocol:    encapsulationProtocol,
		SupportsCIPEncapsulation: supportsCIPEncapsulation,
		SupportsUDP:              supportsUDP,
		Data:                     data,
	}
	_result.TypeIdContract.(*_TypeId)._SubType = _result
	return _result
}

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

// ServicesResponseBuilder is a builder for ServicesResponse
type ServicesResponseBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(encapsulationProtocol uint16, supportsCIPEncapsulation bool, supportsUDP bool, data []byte) ServicesResponseBuilder
	// WithEncapsulationProtocol adds EncapsulationProtocol (property field)
	WithEncapsulationProtocol(uint16) ServicesResponseBuilder
	// WithSupportsCIPEncapsulation adds SupportsCIPEncapsulation (property field)
	WithSupportsCIPEncapsulation(bool) ServicesResponseBuilder
	// WithSupportsUDP adds SupportsUDP (property field)
	WithSupportsUDP(bool) ServicesResponseBuilder
	// WithData adds Data (property field)
	WithData(...byte) ServicesResponseBuilder
	// Done is used to finish work on this child and return (or create one if none) to the parent builder
	Done() TypeIdBuilder
	// Build builds the ServicesResponse or returns an error if something is wrong
	Build() (ServicesResponse, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() ServicesResponse
}

// NewServicesResponseBuilder() creates a ServicesResponseBuilder
func NewServicesResponseBuilder() ServicesResponseBuilder {
	return &_ServicesResponseBuilder{_ServicesResponse: new(_ServicesResponse)}
}

type _ServicesResponseBuilder struct {
	*_ServicesResponse

	parentBuilder *_TypeIdBuilder

	collectedErr []error
}

var _ (ServicesResponseBuilder) = (*_ServicesResponseBuilder)(nil)

func (b *_ServicesResponseBuilder) setParent(contract TypeIdContract) {
	b.TypeIdContract = contract
	contract.(*_TypeId)._SubType = b._ServicesResponse
}

func (b *_ServicesResponseBuilder) WithMandatoryFields(encapsulationProtocol uint16, supportsCIPEncapsulation bool, supportsUDP bool, data []byte) ServicesResponseBuilder {
	return b.WithEncapsulationProtocol(encapsulationProtocol).WithSupportsCIPEncapsulation(supportsCIPEncapsulation).WithSupportsUDP(supportsUDP).WithData(data...)
}

func (b *_ServicesResponseBuilder) WithEncapsulationProtocol(encapsulationProtocol uint16) ServicesResponseBuilder {
	b.EncapsulationProtocol = encapsulationProtocol
	return b
}

func (b *_ServicesResponseBuilder) WithSupportsCIPEncapsulation(supportsCIPEncapsulation bool) ServicesResponseBuilder {
	b.SupportsCIPEncapsulation = supportsCIPEncapsulation
	return b
}

func (b *_ServicesResponseBuilder) WithSupportsUDP(supportsUDP bool) ServicesResponseBuilder {
	b.SupportsUDP = supportsUDP
	return b
}

func (b *_ServicesResponseBuilder) WithData(data ...byte) ServicesResponseBuilder {
	b.Data = data
	return b
}

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

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

func (b *_ServicesResponseBuilder) Done() TypeIdBuilder {
	if b.parentBuilder == nil {
		b.parentBuilder = NewTypeIdBuilder().(*_TypeIdBuilder)
	}
	return b.parentBuilder
}

func (b *_ServicesResponseBuilder) buildForTypeId() (TypeId, error) {
	return b.Build()
}

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

// CreateServicesResponseBuilder creates a ServicesResponseBuilder
func (b *_ServicesResponse) CreateServicesResponseBuilder() ServicesResponseBuilder {
	if b == nil {
		return NewServicesResponseBuilder()
	}
	return &_ServicesResponseBuilder{_ServicesResponse: b.deepCopy()}
}

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

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

func (m *_ServicesResponse) GetId() uint16 {
	return 0x0100
}

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

func (m *_ServicesResponse) GetParent() TypeIdContract {
	return m.TypeIdContract
}

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

func (m *_ServicesResponse) GetEncapsulationProtocol() uint16 {
	return m.EncapsulationProtocol
}

func (m *_ServicesResponse) GetSupportsCIPEncapsulation() bool {
	return m.SupportsCIPEncapsulation
}

func (m *_ServicesResponse) GetSupportsUDP() bool {
	return m.SupportsUDP
}

func (m *_ServicesResponse) GetData() []byte {
	return m.Data
}

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

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

func (m *_ServicesResponse) GetTypeName() string {
	return "ServicesResponse"
}

func (m *_ServicesResponse) GetLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(m.TypeIdContract.(*_TypeId).getLengthInBits(ctx))

	// Implicit Field (serviceLen)
	lengthInBits += 16

	// Simple field (encapsulationProtocol)
	lengthInBits += 16

	// Reserved Field (reserved)
	lengthInBits += 2

	// Simple field (supportsCIPEncapsulation)
	lengthInBits += 1

	// Reserved Field (reserved)
	lengthInBits += 12

	// Simple field (supportsUDP)
	lengthInBits += 1

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

	return lengthInBits
}

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

func (m *_ServicesResponse) parse(ctx context.Context, readBuffer utils.ReadBuffer, parent *_TypeId) (__servicesResponse ServicesResponse, err error) {
	m.TypeIdContract = parent
	parent._SubType = m
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("ServicesResponse"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for ServicesResponse")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

	serviceLen, err := ReadImplicitField[uint16](ctx, "serviceLen", ReadUnsignedShort(readBuffer, uint8(16)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'serviceLen' field"))
	}
	_ = serviceLen

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

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

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

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

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

	data, err := readBuffer.ReadByteArray("data", int(int32(serviceLen)-int32(int32(4))))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'data' field"))
	}
	m.Data = data

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

	return m, nil
}

func (m *_ServicesResponse) 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 *_ServicesResponse) SerializeWithWriteBuffer(ctx context.Context, writeBuffer utils.WriteBuffer) error {
	positionAware := writeBuffer
	_ = positionAware
	log := zerolog.Ctx(ctx)
	_ = log
	ser := func() error {
		if pushErr := writeBuffer.PushContext("ServicesResponse"); pushErr != nil {
			return errors.Wrap(pushErr, "Error pushing for ServicesResponse")
		}
		serviceLen := uint16(uint16(uint16(m.GetLengthInBytes(ctx))) - uint16(uint16(4)))
		if err := WriteImplicitField(ctx, "serviceLen", serviceLen, WriteUnsignedShort(writeBuffer, 16)); err != nil {
			return errors.Wrap(err, "Error serializing 'serviceLen' field")
		}

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

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

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

		if err := WriteReservedField[uint16](ctx, "reserved", uint16(0x00), WriteUnsignedShort(writeBuffer, 12)); err != nil {
			return errors.Wrap(err, "Error serializing 'reserved' field number 2")
		}

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

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

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

func (m *_ServicesResponse) IsServicesResponse() {}

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

func (m *_ServicesResponse) deepCopy() *_ServicesResponse {
	if m == nil {
		return nil
	}
	_ServicesResponseCopy := &_ServicesResponse{
		m.TypeIdContract.(*_TypeId).deepCopy(),
		m.EncapsulationProtocol,
		m.SupportsCIPEncapsulation,
		m.SupportsUDP,
		utils.DeepCopySlice[byte, byte](m.Data),
		m.reservedField0,
		m.reservedField1,
	}
	_ServicesResponseCopy.TypeIdContract.(*_TypeId)._SubType = m
	return _ServicesResponseCopy
}

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