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

// CipReadResponse is the corresponding interface of CipReadResponse
type CipReadResponse interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	CipService
	// GetStatus returns Status (property field)
	GetStatus() uint8
	// GetExtStatus returns ExtStatus (property field)
	GetExtStatus() uint8
	// GetData returns Data (property field)
	GetData() CIPData
	// IsCipReadResponse is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsCipReadResponse()
	// CreateBuilder creates a CipReadResponseBuilder
	CreateCipReadResponseBuilder() CipReadResponseBuilder
}

// _CipReadResponse is the data-structure of this message
type _CipReadResponse struct {
	CipServiceContract
	Status    uint8
	ExtStatus uint8
	Data      CIPData
	// Reserved Fields
	reservedField0 *uint8
}

var _ CipReadResponse = (*_CipReadResponse)(nil)
var _ CipServiceRequirements = (*_CipReadResponse)(nil)

// NewCipReadResponse factory function for _CipReadResponse
func NewCipReadResponse(status uint8, extStatus uint8, data CIPData) *_CipReadResponse {
	_result := &_CipReadResponse{
		CipServiceContract: NewCipService(),
		Status:             status,
		ExtStatus:          extStatus,
		Data:               data,
	}
	_result.CipServiceContract.(*_CipService)._SubType = _result
	return _result
}

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

// CipReadResponseBuilder is a builder for CipReadResponse
type CipReadResponseBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(status uint8, extStatus uint8) CipReadResponseBuilder
	// WithStatus adds Status (property field)
	WithStatus(uint8) CipReadResponseBuilder
	// WithExtStatus adds ExtStatus (property field)
	WithExtStatus(uint8) CipReadResponseBuilder
	// WithData adds Data (property field)
	WithOptionalData(CIPData) CipReadResponseBuilder
	// WithOptionalDataBuilder adds Data (property field) which is build by the builder
	WithOptionalDataBuilder(func(CIPDataBuilder) CIPDataBuilder) CipReadResponseBuilder
	// 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 CipReadResponse or returns an error if something is wrong
	Build() (CipReadResponse, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() CipReadResponse
}

// NewCipReadResponseBuilder() creates a CipReadResponseBuilder
func NewCipReadResponseBuilder() CipReadResponseBuilder {
	return &_CipReadResponseBuilder{_CipReadResponse: new(_CipReadResponse)}
}

type _CipReadResponseBuilder struct {
	*_CipReadResponse

	parentBuilder *_CipServiceBuilder

	collectedErr []error
}

var _ (CipReadResponseBuilder) = (*_CipReadResponseBuilder)(nil)

func (b *_CipReadResponseBuilder) setParent(contract CipServiceContract) {
	b.CipServiceContract = contract
	contract.(*_CipService)._SubType = b._CipReadResponse
}

func (b *_CipReadResponseBuilder) WithMandatoryFields(status uint8, extStatus uint8) CipReadResponseBuilder {
	return b.WithStatus(status).WithExtStatus(extStatus)
}

func (b *_CipReadResponseBuilder) WithStatus(status uint8) CipReadResponseBuilder {
	b.Status = status
	return b
}

func (b *_CipReadResponseBuilder) WithExtStatus(extStatus uint8) CipReadResponseBuilder {
	b.ExtStatus = extStatus
	return b
}

func (b *_CipReadResponseBuilder) WithOptionalData(data CIPData) CipReadResponseBuilder {
	b.Data = data
	return b
}

func (b *_CipReadResponseBuilder) WithOptionalDataBuilder(builderSupplier func(CIPDataBuilder) CIPDataBuilder) CipReadResponseBuilder {
	builder := builderSupplier(b.Data.CreateCIPDataBuilder())
	var err error
	b.Data, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "CIPDataBuilder failed"))
	}
	return b
}

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

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

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

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

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

// CreateCipReadResponseBuilder creates a CipReadResponseBuilder
func (b *_CipReadResponse) CreateCipReadResponseBuilder() CipReadResponseBuilder {
	if b == nil {
		return NewCipReadResponseBuilder()
	}
	return &_CipReadResponseBuilder{_CipReadResponse: b.deepCopy()}
}

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

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

func (m *_CipReadResponse) GetService() uint8 {
	return 0x4C
}

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

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

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

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

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

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

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

func (m *_CipReadResponse) GetData() CIPData {
	return m.Data
}

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

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

func (m *_CipReadResponse) GetTypeName() string {
	return "CipReadResponse"
}

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

	// Optional Field (data)
	if m.Data != nil {
		lengthInBits += m.Data.GetLengthInBits(ctx)
	}

	return lengthInBits
}

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

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

	reservedField0, err := ReadReservedField(ctx, "reserved", ReadUnsignedByte(readBuffer, uint8(8)), uint8(0x00))
	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

	var data CIPData
	_data, err := ReadOptionalField[CIPData](ctx, "data", ReadComplex[CIPData](CIPDataParseWithBufferProducer((uint16)(uint16(serviceLen)-uint16(uint16(4)))), readBuffer), bool(((serviceLen)-(4)) > (0)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'data' field"))
	}
	if _data != nil {
		data = *_data
		m.Data = data
	}

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

	return m, nil
}

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

		if err := WriteReservedField[uint8](ctx, "reserved", uint8(0x00), 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 := WriteOptionalField[CIPData](ctx, "data", GetRef(m.GetData()), WriteComplex[CIPData](writeBuffer), true); err != nil {
			return errors.Wrap(err, "Error serializing 'data' field")
		}

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

func (m *_CipReadResponse) IsCipReadResponse() {}

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

func (m *_CipReadResponse) deepCopy() *_CipReadResponse {
	if m == nil {
		return nil
	}
	_CipReadResponseCopy := &_CipReadResponse{
		m.CipServiceContract.(*_CipService).deepCopy(),
		m.Status,
		m.ExtStatus,
		utils.DeepCopy[CIPData](m.Data),
		m.reservedField0,
	}
	_CipReadResponseCopy.CipServiceContract.(*_CipService)._SubType = m
	return _CipReadResponseCopy
}

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