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

// S7MessageResponse is the corresponding interface of S7MessageResponse
type S7MessageResponse interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	S7Message
	// GetErrorClass returns ErrorClass (property field)
	GetErrorClass() uint8
	// GetErrorCode returns ErrorCode (property field)
	GetErrorCode() uint8
	// IsS7MessageResponse is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsS7MessageResponse()
	// CreateBuilder creates a S7MessageResponseBuilder
	CreateS7MessageResponseBuilder() S7MessageResponseBuilder
}

// _S7MessageResponse is the data-structure of this message
type _S7MessageResponse struct {
	S7MessageContract
	ErrorClass uint8
	ErrorCode  uint8
}

var _ S7MessageResponse = (*_S7MessageResponse)(nil)
var _ S7MessageRequirements = (*_S7MessageResponse)(nil)

// NewS7MessageResponse factory function for _S7MessageResponse
func NewS7MessageResponse(tpduReference uint16, parameter S7Parameter, payload S7Payload, errorClass uint8, errorCode uint8) *_S7MessageResponse {
	_result := &_S7MessageResponse{
		S7MessageContract: NewS7Message(tpduReference, parameter, payload),
		ErrorClass:        errorClass,
		ErrorCode:         errorCode,
	}
	_result.S7MessageContract.(*_S7Message)._SubType = _result
	return _result
}

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

// S7MessageResponseBuilder is a builder for S7MessageResponse
type S7MessageResponseBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(errorClass uint8, errorCode uint8) S7MessageResponseBuilder
	// WithErrorClass adds ErrorClass (property field)
	WithErrorClass(uint8) S7MessageResponseBuilder
	// WithErrorCode adds ErrorCode (property field)
	WithErrorCode(uint8) S7MessageResponseBuilder
	// Done is used to finish work on this child and return (or create one if none) to the parent builder
	Done() S7MessageBuilder
	// Build builds the S7MessageResponse or returns an error if something is wrong
	Build() (S7MessageResponse, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() S7MessageResponse
}

// NewS7MessageResponseBuilder() creates a S7MessageResponseBuilder
func NewS7MessageResponseBuilder() S7MessageResponseBuilder {
	return &_S7MessageResponseBuilder{_S7MessageResponse: new(_S7MessageResponse)}
}

type _S7MessageResponseBuilder struct {
	*_S7MessageResponse

	parentBuilder *_S7MessageBuilder

	collectedErr []error
}

var _ (S7MessageResponseBuilder) = (*_S7MessageResponseBuilder)(nil)

func (b *_S7MessageResponseBuilder) setParent(contract S7MessageContract) {
	b.S7MessageContract = contract
	contract.(*_S7Message)._SubType = b._S7MessageResponse
}

func (b *_S7MessageResponseBuilder) WithMandatoryFields(errorClass uint8, errorCode uint8) S7MessageResponseBuilder {
	return b.WithErrorClass(errorClass).WithErrorCode(errorCode)
}

func (b *_S7MessageResponseBuilder) WithErrorClass(errorClass uint8) S7MessageResponseBuilder {
	b.ErrorClass = errorClass
	return b
}

func (b *_S7MessageResponseBuilder) WithErrorCode(errorCode uint8) S7MessageResponseBuilder {
	b.ErrorCode = errorCode
	return b
}

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

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

func (b *_S7MessageResponseBuilder) Done() S7MessageBuilder {
	if b.parentBuilder == nil {
		b.parentBuilder = NewS7MessageBuilder().(*_S7MessageBuilder)
	}
	return b.parentBuilder
}

func (b *_S7MessageResponseBuilder) buildForS7Message() (S7Message, error) {
	return b.Build()
}

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

// CreateS7MessageResponseBuilder creates a S7MessageResponseBuilder
func (b *_S7MessageResponse) CreateS7MessageResponseBuilder() S7MessageResponseBuilder {
	if b == nil {
		return NewS7MessageResponseBuilder()
	}
	return &_S7MessageResponseBuilder{_S7MessageResponse: b.deepCopy()}
}

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

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

func (m *_S7MessageResponse) GetMessageType() uint8 {
	return 0x02
}

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

func (m *_S7MessageResponse) GetParent() S7MessageContract {
	return m.S7MessageContract
}

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

func (m *_S7MessageResponse) GetErrorClass() uint8 {
	return m.ErrorClass
}

func (m *_S7MessageResponse) GetErrorCode() uint8 {
	return m.ErrorCode
}

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

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

func (m *_S7MessageResponse) GetTypeName() string {
	return "S7MessageResponse"
}

func (m *_S7MessageResponse) GetLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(m.S7MessageContract.(*_S7Message).getLengthInBits(ctx))

	// Simple field (errorClass)
	lengthInBits += 8

	// Simple field (errorCode)
	lengthInBits += 8

	return lengthInBits
}

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

func (m *_S7MessageResponse) parse(ctx context.Context, readBuffer utils.ReadBuffer, parent *_S7Message) (__s7MessageResponse S7MessageResponse, err error) {
	m.S7MessageContract = parent
	parent._SubType = m
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("S7MessageResponse"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for S7MessageResponse")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

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

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

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

	return m, nil
}

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

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

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

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

func (m *_S7MessageResponse) IsS7MessageResponse() {}

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

func (m *_S7MessageResponse) deepCopy() *_S7MessageResponse {
	if m == nil {
		return nil
	}
	_S7MessageResponseCopy := &_S7MessageResponse{
		m.S7MessageContract.(*_S7Message).deepCopy(),
		m.ErrorClass,
		m.ErrorCode,
	}
	_S7MessageResponseCopy.S7MessageContract.(*_S7Message)._SubType = m
	return _S7MessageResponseCopy
}

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