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

// RedundantServerDataType is the corresponding interface of RedundantServerDataType
type RedundantServerDataType interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetServerId returns ServerId (property field)
	GetServerId() PascalString
	// GetServiceLevel returns ServiceLevel (property field)
	GetServiceLevel() uint8
	// GetServerState returns ServerState (property field)
	GetServerState() ServerState
	// IsRedundantServerDataType is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsRedundantServerDataType()
	// CreateBuilder creates a RedundantServerDataTypeBuilder
	CreateRedundantServerDataTypeBuilder() RedundantServerDataTypeBuilder
}

// _RedundantServerDataType is the data-structure of this message
type _RedundantServerDataType struct {
	ExtensionObjectDefinitionContract
	ServerId     PascalString
	ServiceLevel uint8
	ServerState  ServerState
}

var _ RedundantServerDataType = (*_RedundantServerDataType)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_RedundantServerDataType)(nil)

// NewRedundantServerDataType factory function for _RedundantServerDataType
func NewRedundantServerDataType(serverId PascalString, serviceLevel uint8, serverState ServerState) *_RedundantServerDataType {
	if serverId == nil {
		panic("serverId of type PascalString for RedundantServerDataType must not be nil")
	}
	_result := &_RedundantServerDataType{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		ServerId:                          serverId,
		ServiceLevel:                      serviceLevel,
		ServerState:                       serverState,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// RedundantServerDataTypeBuilder is a builder for RedundantServerDataType
type RedundantServerDataTypeBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(serverId PascalString, serviceLevel uint8, serverState ServerState) RedundantServerDataTypeBuilder
	// WithServerId adds ServerId (property field)
	WithServerId(PascalString) RedundantServerDataTypeBuilder
	// WithServerIdBuilder adds ServerId (property field) which is build by the builder
	WithServerIdBuilder(func(PascalStringBuilder) PascalStringBuilder) RedundantServerDataTypeBuilder
	// WithServiceLevel adds ServiceLevel (property field)
	WithServiceLevel(uint8) RedundantServerDataTypeBuilder
	// WithServerState adds ServerState (property field)
	WithServerState(ServerState) RedundantServerDataTypeBuilder
	// 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 RedundantServerDataType or returns an error if something is wrong
	Build() (RedundantServerDataType, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() RedundantServerDataType
}

// NewRedundantServerDataTypeBuilder() creates a RedundantServerDataTypeBuilder
func NewRedundantServerDataTypeBuilder() RedundantServerDataTypeBuilder {
	return &_RedundantServerDataTypeBuilder{_RedundantServerDataType: new(_RedundantServerDataType)}
}

type _RedundantServerDataTypeBuilder struct {
	*_RedundantServerDataType

	parentBuilder *_ExtensionObjectDefinitionBuilder

	collectedErr []error
}

var _ (RedundantServerDataTypeBuilder) = (*_RedundantServerDataTypeBuilder)(nil)

func (b *_RedundantServerDataTypeBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._RedundantServerDataType
}

func (b *_RedundantServerDataTypeBuilder) WithMandatoryFields(serverId PascalString, serviceLevel uint8, serverState ServerState) RedundantServerDataTypeBuilder {
	return b.WithServerId(serverId).WithServiceLevel(serviceLevel).WithServerState(serverState)
}

func (b *_RedundantServerDataTypeBuilder) WithServerId(serverId PascalString) RedundantServerDataTypeBuilder {
	b.ServerId = serverId
	return b
}

func (b *_RedundantServerDataTypeBuilder) WithServerIdBuilder(builderSupplier func(PascalStringBuilder) PascalStringBuilder) RedundantServerDataTypeBuilder {
	builder := builderSupplier(b.ServerId.CreatePascalStringBuilder())
	var err error
	b.ServerId, err = builder.Build()
	if err != nil {
		b.collectedErr = append(b.collectedErr, errors.Wrap(err, "PascalStringBuilder failed"))
	}
	return b
}

func (b *_RedundantServerDataTypeBuilder) WithServiceLevel(serviceLevel uint8) RedundantServerDataTypeBuilder {
	b.ServiceLevel = serviceLevel
	return b
}

func (b *_RedundantServerDataTypeBuilder) WithServerState(serverState ServerState) RedundantServerDataTypeBuilder {
	b.ServerState = serverState
	return b
}

func (b *_RedundantServerDataTypeBuilder) Build() (RedundantServerDataType, error) {
	if b.ServerId == nil {
		b.collectedErr = append(b.collectedErr, errors.New("mandatory field 'serverId' not set"))
	}
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._RedundantServerDataType.deepCopy(), nil
}

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

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

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

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

// CreateRedundantServerDataTypeBuilder creates a RedundantServerDataTypeBuilder
func (b *_RedundantServerDataType) CreateRedundantServerDataTypeBuilder() RedundantServerDataTypeBuilder {
	if b == nil {
		return NewRedundantServerDataTypeBuilder()
	}
	return &_RedundantServerDataTypeBuilder{_RedundantServerDataType: b.deepCopy()}
}

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

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

func (m *_RedundantServerDataType) GetExtensionId() int32 {
	return int32(855)
}

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

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

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

func (m *_RedundantServerDataType) GetServerId() PascalString {
	return m.ServerId
}

func (m *_RedundantServerDataType) GetServiceLevel() uint8 {
	return m.ServiceLevel
}

func (m *_RedundantServerDataType) GetServerState() ServerState {
	return m.ServerState
}

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

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

func (m *_RedundantServerDataType) GetTypeName() string {
	return "RedundantServerDataType"
}

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

	// Simple field (serverId)
	lengthInBits += m.ServerId.GetLengthInBits(ctx)

	// Simple field (serviceLevel)
	lengthInBits += 8

	// Simple field (serverState)
	lengthInBits += 32

	return lengthInBits
}

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

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

	serverId, err := ReadSimpleField[PascalString](ctx, "serverId", ReadComplex[PascalString](PascalStringParseWithBuffer, readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'serverId' field"))
	}
	m.ServerId = serverId

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

	serverState, err := ReadEnumField[ServerState](ctx, "serverState", "ServerState", ReadEnum(ServerStateByValue, ReadUnsignedInt(readBuffer, uint8(32))))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'serverState' field"))
	}
	m.ServerState = serverState

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

	return m, nil
}

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

		if err := WriteSimpleField[PascalString](ctx, "serverId", m.GetServerId(), WriteComplex[PascalString](writeBuffer)); err != nil {
			return errors.Wrap(err, "Error serializing 'serverId' field")
		}

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

		if err := WriteSimpleEnumField[ServerState](ctx, "serverState", "ServerState", m.GetServerState(), WriteEnum[ServerState, uint32](ServerState.GetValue, ServerState.PLC4XEnumName, WriteUnsignedInt(writeBuffer, 32))); err != nil {
			return errors.Wrap(err, "Error serializing 'serverState' field")
		}

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

func (m *_RedundantServerDataType) IsRedundantServerDataType() {}

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

func (m *_RedundantServerDataType) deepCopy() *_RedundantServerDataType {
	if m == nil {
		return nil
	}
	_RedundantServerDataTypeCopy := &_RedundantServerDataType{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[PascalString](m.ServerId),
		m.ServiceLevel,
		m.ServerState,
	}
	_RedundantServerDataTypeCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _RedundantServerDataTypeCopy
}

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