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

// ServiceId is the corresponding interface of ServiceId
type ServiceId interface {
	ServiceIdContract
	ServiceIdRequirements
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	// IsServiceId is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsServiceId()
	// CreateBuilder creates a ServiceIdBuilder
	CreateServiceIdBuilder() ServiceIdBuilder
}

// ServiceIdContract provides a set of functions which can be overwritten by a sub struct
type ServiceIdContract interface {
	// IsServiceId is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsServiceId()
	// CreateBuilder creates a ServiceIdBuilder
	CreateServiceIdBuilder() ServiceIdBuilder
}

// ServiceIdRequirements provides a set of functions which need to be implemented by a sub struct
type ServiceIdRequirements interface {
	GetLengthInBits(ctx context.Context) uint16
	GetLengthInBytes(ctx context.Context) uint16
	// GetServiceType returns ServiceType (discriminator field)
	GetServiceType() uint8
}

// _ServiceId is the data-structure of this message
type _ServiceId struct {
	_SubType interface {
		ServiceIdContract
		ServiceIdRequirements
	}
}

var _ ServiceIdContract = (*_ServiceId)(nil)

// NewServiceId factory function for _ServiceId
func NewServiceId() *_ServiceId {
	return &_ServiceId{}
}

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

// ServiceIdBuilder is a builder for ServiceId
type ServiceIdBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields() ServiceIdBuilder
	// AsKnxNetIpCore converts this build to a subType of ServiceId. It is always possible to return to current builder using Done()
	AsKnxNetIpCore() KnxNetIpCoreBuilder
	// AsKnxNetIpDeviceManagement converts this build to a subType of ServiceId. It is always possible to return to current builder using Done()
	AsKnxNetIpDeviceManagement() KnxNetIpDeviceManagementBuilder
	// AsKnxNetIpTunneling converts this build to a subType of ServiceId. It is always possible to return to current builder using Done()
	AsKnxNetIpTunneling() KnxNetIpTunnelingBuilder
	// AsKnxNetIpRouting converts this build to a subType of ServiceId. It is always possible to return to current builder using Done()
	AsKnxNetIpRouting() KnxNetIpRoutingBuilder
	// AsKnxNetRemoteLogging converts this build to a subType of ServiceId. It is always possible to return to current builder using Done()
	AsKnxNetRemoteLogging() KnxNetRemoteLoggingBuilder
	// AsKnxNetRemoteConfigurationAndDiagnosis converts this build to a subType of ServiceId. It is always possible to return to current builder using Done()
	AsKnxNetRemoteConfigurationAndDiagnosis() KnxNetRemoteConfigurationAndDiagnosisBuilder
	// AsKnxNetObjectServer converts this build to a subType of ServiceId. It is always possible to return to current builder using Done()
	AsKnxNetObjectServer() KnxNetObjectServerBuilder
	// Build builds the ServiceId or returns an error if something is wrong
	PartialBuild() (ServiceIdContract, error)
	// MustBuild does the same as Build but panics on error
	PartialMustBuild() ServiceIdContract
	// Build builds the ServiceId or returns an error if something is wrong
	Build() (ServiceId, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() ServiceId
}

// NewServiceIdBuilder() creates a ServiceIdBuilder
func NewServiceIdBuilder() ServiceIdBuilder {
	return &_ServiceIdBuilder{_ServiceId: new(_ServiceId)}
}

type _ServiceIdChildBuilder interface {
	utils.Copyable
	setParent(ServiceIdContract)
	buildForServiceId() (ServiceId, error)
}

type _ServiceIdBuilder struct {
	*_ServiceId

	childBuilder _ServiceIdChildBuilder

	collectedErr []error
}

var _ (ServiceIdBuilder) = (*_ServiceIdBuilder)(nil)

func (b *_ServiceIdBuilder) WithMandatoryFields() ServiceIdBuilder {
	return b
}

func (b *_ServiceIdBuilder) PartialBuild() (ServiceIdContract, error) {
	if err := stdErrors.Join(b.collectedErr...); err != nil {
		return nil, errors.Wrap(err, "error occurred during build")
	}
	return b._ServiceId.deepCopy(), nil
}

func (b *_ServiceIdBuilder) PartialMustBuild() ServiceIdContract {
	build, err := b.PartialBuild()
	if err != nil {
		panic(err)
	}
	return build
}

func (b *_ServiceIdBuilder) AsKnxNetIpCore() KnxNetIpCoreBuilder {
	if cb, ok := b.childBuilder.(KnxNetIpCoreBuilder); ok {
		return cb
	}
	cb := NewKnxNetIpCoreBuilder().(*_KnxNetIpCoreBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_ServiceIdBuilder) AsKnxNetIpDeviceManagement() KnxNetIpDeviceManagementBuilder {
	if cb, ok := b.childBuilder.(KnxNetIpDeviceManagementBuilder); ok {
		return cb
	}
	cb := NewKnxNetIpDeviceManagementBuilder().(*_KnxNetIpDeviceManagementBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_ServiceIdBuilder) AsKnxNetIpTunneling() KnxNetIpTunnelingBuilder {
	if cb, ok := b.childBuilder.(KnxNetIpTunnelingBuilder); ok {
		return cb
	}
	cb := NewKnxNetIpTunnelingBuilder().(*_KnxNetIpTunnelingBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_ServiceIdBuilder) AsKnxNetIpRouting() KnxNetIpRoutingBuilder {
	if cb, ok := b.childBuilder.(KnxNetIpRoutingBuilder); ok {
		return cb
	}
	cb := NewKnxNetIpRoutingBuilder().(*_KnxNetIpRoutingBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_ServiceIdBuilder) AsKnxNetRemoteLogging() KnxNetRemoteLoggingBuilder {
	if cb, ok := b.childBuilder.(KnxNetRemoteLoggingBuilder); ok {
		return cb
	}
	cb := NewKnxNetRemoteLoggingBuilder().(*_KnxNetRemoteLoggingBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_ServiceIdBuilder) AsKnxNetRemoteConfigurationAndDiagnosis() KnxNetRemoteConfigurationAndDiagnosisBuilder {
	if cb, ok := b.childBuilder.(KnxNetRemoteConfigurationAndDiagnosisBuilder); ok {
		return cb
	}
	cb := NewKnxNetRemoteConfigurationAndDiagnosisBuilder().(*_KnxNetRemoteConfigurationAndDiagnosisBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_ServiceIdBuilder) AsKnxNetObjectServer() KnxNetObjectServerBuilder {
	if cb, ok := b.childBuilder.(KnxNetObjectServerBuilder); ok {
		return cb
	}
	cb := NewKnxNetObjectServerBuilder().(*_KnxNetObjectServerBuilder)
	cb.parentBuilder = b
	b.childBuilder = cb
	return cb
}

func (b *_ServiceIdBuilder) Build() (ServiceId, error) {
	v, err := b.PartialBuild()
	if err != nil {
		return nil, errors.Wrap(err, "error occurred during partial build")
	}
	if b.childBuilder == nil {
		return nil, errors.New("no child builder present")
	}
	b.childBuilder.setParent(v)
	return b.childBuilder.buildForServiceId()
}

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

func (b *_ServiceIdBuilder) DeepCopy() any {
	_copy := b.CreateServiceIdBuilder().(*_ServiceIdBuilder)
	_copy.childBuilder = b.childBuilder.DeepCopy().(_ServiceIdChildBuilder)
	_copy.childBuilder.setParent(_copy)
	if b.collectedErr != nil {
		copy(_copy.collectedErr, b.collectedErr)
	}
	return _copy
}

// CreateServiceIdBuilder creates a ServiceIdBuilder
func (b *_ServiceId) CreateServiceIdBuilder() ServiceIdBuilder {
	if b == nil {
		return NewServiceIdBuilder()
	}
	return &_ServiceIdBuilder{_ServiceId: b.deepCopy()}
}

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

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

func (m *_ServiceId) GetTypeName() string {
	return "ServiceId"
}

func (m *_ServiceId) getLengthInBits(ctx context.Context) uint16 {
	lengthInBits := uint16(0)
	// Discriminator Field (serviceType)
	lengthInBits += 8

	return lengthInBits
}

func (m *_ServiceId) GetLengthInBits(ctx context.Context) uint16 {
	return m._SubType.GetLengthInBits(ctx)
}

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

func ServiceIdParse[T ServiceId](ctx context.Context, theBytes []byte) (T, error) {
	return ServiceIdParseWithBuffer[T](ctx, utils.NewReadBufferByteBased(theBytes))
}

func ServiceIdParseWithBufferProducer[T ServiceId]() func(ctx context.Context, readBuffer utils.ReadBuffer) (T, error) {
	return func(ctx context.Context, readBuffer utils.ReadBuffer) (T, error) {
		v, err := ServiceIdParseWithBuffer[T](ctx, readBuffer)
		if err != nil {
			var zero T
			return zero, err
		}
		return v, nil
	}
}

func ServiceIdParseWithBuffer[T ServiceId](ctx context.Context, readBuffer utils.ReadBuffer) (T, error) {
	v, err := (new(_ServiceId)).parse(ctx, readBuffer)
	if err != nil {
		var zero T
		return zero, err
	}
	vc, ok := v.(T)
	if !ok {
		var zero T
		return zero, errors.Errorf("Unexpected type %T. Expected type %T", v, *new(T))
	}
	return vc, nil
}

func (m *_ServiceId) parse(ctx context.Context, readBuffer utils.ReadBuffer) (__serviceId ServiceId, err error) {
	positionAware := readBuffer
	_ = positionAware
	if pullErr := readBuffer.PullContext("ServiceId"); pullErr != nil {
		return nil, errors.Wrap(pullErr, "Error pulling for ServiceId")
	}
	currentPos := positionAware.GetPos()
	_ = currentPos

	serviceType, err := ReadDiscriminatorField[uint8](ctx, "serviceType", ReadUnsignedByte(readBuffer, uint8(8)))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'serviceType' field"))
	}

	// Switch Field (Depending on the discriminator values, passes the instantiation to a sub-type)
	var _child ServiceId
	switch {
	case serviceType == 0x02: // KnxNetIpCore
		if _child, err = new(_KnxNetIpCore).parse(ctx, readBuffer, m); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type KnxNetIpCore for type-switch of ServiceId")
		}
	case serviceType == 0x03: // KnxNetIpDeviceManagement
		if _child, err = new(_KnxNetIpDeviceManagement).parse(ctx, readBuffer, m); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type KnxNetIpDeviceManagement for type-switch of ServiceId")
		}
	case serviceType == 0x04: // KnxNetIpTunneling
		if _child, err = new(_KnxNetIpTunneling).parse(ctx, readBuffer, m); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type KnxNetIpTunneling for type-switch of ServiceId")
		}
	case serviceType == 0x05: // KnxNetIpRouting
		if _child, err = new(_KnxNetIpRouting).parse(ctx, readBuffer, m); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type KnxNetIpRouting for type-switch of ServiceId")
		}
	case serviceType == 0x06: // KnxNetRemoteLogging
		if _child, err = new(_KnxNetRemoteLogging).parse(ctx, readBuffer, m); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type KnxNetRemoteLogging for type-switch of ServiceId")
		}
	case serviceType == 0x07: // KnxNetRemoteConfigurationAndDiagnosis
		if _child, err = new(_KnxNetRemoteConfigurationAndDiagnosis).parse(ctx, readBuffer, m); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type KnxNetRemoteConfigurationAndDiagnosis for type-switch of ServiceId")
		}
	case serviceType == 0x08: // KnxNetObjectServer
		if _child, err = new(_KnxNetObjectServer).parse(ctx, readBuffer, m); err != nil {
			return nil, errors.Wrap(err, "Error parsing sub-type KnxNetObjectServer for type-switch of ServiceId")
		}
	default:
		return nil, errors.Errorf("Unmapped type for parameters [serviceType=%v]", serviceType)
	}

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

	return _child, nil
}

func (pm *_ServiceId) serializeParent(ctx context.Context, writeBuffer utils.WriteBuffer, child ServiceId, serializeChildFunction func() error) error {
	// We redirect all calls through client as some methods are only implemented there
	m := child
	_ = m
	positionAware := writeBuffer
	_ = positionAware
	log := zerolog.Ctx(ctx)
	_ = log
	if pushErr := writeBuffer.PushContext("ServiceId"); pushErr != nil {
		return errors.Wrap(pushErr, "Error pushing for ServiceId")
	}

	if err := WriteDiscriminatorField(ctx, "serviceType", m.GetServiceType(), WriteUnsignedByte(writeBuffer, 8)); err != nil {
		return errors.Wrap(err, "Error serializing 'serviceType' field")
	}

	// Switch field (Depending on the discriminator values, passes the serialization to a sub-type)
	if _typeSwitchErr := serializeChildFunction(); _typeSwitchErr != nil {
		return errors.Wrap(_typeSwitchErr, "Error serializing sub-type field")
	}

	if popErr := writeBuffer.PopContext("ServiceId"); popErr != nil {
		return errors.Wrap(popErr, "Error popping for ServiceId")
	}
	return nil
}

func (m *_ServiceId) IsServiceId() {}

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

func (m *_ServiceId) deepCopy() *_ServiceId {
	if m == nil {
		return nil
	}
	_ServiceIdCopy := &_ServiceId{
		nil, // will be set by child
	}
	return _ServiceIdCopy
}
