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

// HistoryReadResult is the corresponding interface of HistoryReadResult
type HistoryReadResult interface {
	fmt.Stringer
	utils.LengthAware
	utils.Serializable
	utils.Copyable
	ExtensionObjectDefinition
	// GetStatusCode returns StatusCode (property field)
	GetStatusCode() StatusCode
	// GetContinuationPoint returns ContinuationPoint (property field)
	GetContinuationPoint() PascalByteString
	// GetHistoryData returns HistoryData (property field)
	GetHistoryData() ExtensionObject
	// IsHistoryReadResult is a marker method to prevent unintentional type checks (interfaces of same signature)
	IsHistoryReadResult()
	// CreateBuilder creates a HistoryReadResultBuilder
	CreateHistoryReadResultBuilder() HistoryReadResultBuilder
}

// _HistoryReadResult is the data-structure of this message
type _HistoryReadResult struct {
	ExtensionObjectDefinitionContract
	StatusCode        StatusCode
	ContinuationPoint PascalByteString
	HistoryData       ExtensionObject
}

var _ HistoryReadResult = (*_HistoryReadResult)(nil)
var _ ExtensionObjectDefinitionRequirements = (*_HistoryReadResult)(nil)

// NewHistoryReadResult factory function for _HistoryReadResult
func NewHistoryReadResult(statusCode StatusCode, continuationPoint PascalByteString, historyData ExtensionObject) *_HistoryReadResult {
	if statusCode == nil {
		panic("statusCode of type StatusCode for HistoryReadResult must not be nil")
	}
	if continuationPoint == nil {
		panic("continuationPoint of type PascalByteString for HistoryReadResult must not be nil")
	}
	if historyData == nil {
		panic("historyData of type ExtensionObject for HistoryReadResult must not be nil")
	}
	_result := &_HistoryReadResult{
		ExtensionObjectDefinitionContract: NewExtensionObjectDefinition(),
		StatusCode:                        statusCode,
		ContinuationPoint:                 continuationPoint,
		HistoryData:                       historyData,
	}
	_result.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = _result
	return _result
}

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

// HistoryReadResultBuilder is a builder for HistoryReadResult
type HistoryReadResultBuilder interface {
	utils.Copyable
	// WithMandatoryFields adds all mandatory fields (convenience for using multiple builder calls)
	WithMandatoryFields(statusCode StatusCode, continuationPoint PascalByteString, historyData ExtensionObject) HistoryReadResultBuilder
	// WithStatusCode adds StatusCode (property field)
	WithStatusCode(StatusCode) HistoryReadResultBuilder
	// WithStatusCodeBuilder adds StatusCode (property field) which is build by the builder
	WithStatusCodeBuilder(func(StatusCodeBuilder) StatusCodeBuilder) HistoryReadResultBuilder
	// WithContinuationPoint adds ContinuationPoint (property field)
	WithContinuationPoint(PascalByteString) HistoryReadResultBuilder
	// WithContinuationPointBuilder adds ContinuationPoint (property field) which is build by the builder
	WithContinuationPointBuilder(func(PascalByteStringBuilder) PascalByteStringBuilder) HistoryReadResultBuilder
	// WithHistoryData adds HistoryData (property field)
	WithHistoryData(ExtensionObject) HistoryReadResultBuilder
	// WithHistoryDataBuilder adds HistoryData (property field) which is build by the builder
	WithHistoryDataBuilder(func(ExtensionObjectBuilder) ExtensionObjectBuilder) HistoryReadResultBuilder
	// 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 HistoryReadResult or returns an error if something is wrong
	Build() (HistoryReadResult, error)
	// MustBuild does the same as Build but panics on error
	MustBuild() HistoryReadResult
}

// NewHistoryReadResultBuilder() creates a HistoryReadResultBuilder
func NewHistoryReadResultBuilder() HistoryReadResultBuilder {
	return &_HistoryReadResultBuilder{_HistoryReadResult: new(_HistoryReadResult)}
}

type _HistoryReadResultBuilder struct {
	*_HistoryReadResult

	parentBuilder *_ExtensionObjectDefinitionBuilder

	err *utils.MultiError
}

var _ (HistoryReadResultBuilder) = (*_HistoryReadResultBuilder)(nil)

func (b *_HistoryReadResultBuilder) setParent(contract ExtensionObjectDefinitionContract) {
	b.ExtensionObjectDefinitionContract = contract
	contract.(*_ExtensionObjectDefinition)._SubType = b._HistoryReadResult
}

func (b *_HistoryReadResultBuilder) WithMandatoryFields(statusCode StatusCode, continuationPoint PascalByteString, historyData ExtensionObject) HistoryReadResultBuilder {
	return b.WithStatusCode(statusCode).WithContinuationPoint(continuationPoint).WithHistoryData(historyData)
}

func (b *_HistoryReadResultBuilder) WithStatusCode(statusCode StatusCode) HistoryReadResultBuilder {
	b.StatusCode = statusCode
	return b
}

func (b *_HistoryReadResultBuilder) WithStatusCodeBuilder(builderSupplier func(StatusCodeBuilder) StatusCodeBuilder) HistoryReadResultBuilder {
	builder := builderSupplier(b.StatusCode.CreateStatusCodeBuilder())
	var err error
	b.StatusCode, err = builder.Build()
	if err != nil {
		if b.err == nil {
			b.err = &utils.MultiError{MainError: errors.New("sub builder failed")}
		}
		b.err.Append(errors.Wrap(err, "StatusCodeBuilder failed"))
	}
	return b
}

func (b *_HistoryReadResultBuilder) WithContinuationPoint(continuationPoint PascalByteString) HistoryReadResultBuilder {
	b.ContinuationPoint = continuationPoint
	return b
}

func (b *_HistoryReadResultBuilder) WithContinuationPointBuilder(builderSupplier func(PascalByteStringBuilder) PascalByteStringBuilder) HistoryReadResultBuilder {
	builder := builderSupplier(b.ContinuationPoint.CreatePascalByteStringBuilder())
	var err error
	b.ContinuationPoint, err = builder.Build()
	if err != nil {
		if b.err == nil {
			b.err = &utils.MultiError{MainError: errors.New("sub builder failed")}
		}
		b.err.Append(errors.Wrap(err, "PascalByteStringBuilder failed"))
	}
	return b
}

func (b *_HistoryReadResultBuilder) WithHistoryData(historyData ExtensionObject) HistoryReadResultBuilder {
	b.HistoryData = historyData
	return b
}

func (b *_HistoryReadResultBuilder) WithHistoryDataBuilder(builderSupplier func(ExtensionObjectBuilder) ExtensionObjectBuilder) HistoryReadResultBuilder {
	builder := builderSupplier(b.HistoryData.CreateExtensionObjectBuilder())
	var err error
	b.HistoryData, err = builder.Build()
	if err != nil {
		if b.err == nil {
			b.err = &utils.MultiError{MainError: errors.New("sub builder failed")}
		}
		b.err.Append(errors.Wrap(err, "ExtensionObjectBuilder failed"))
	}
	return b
}

func (b *_HistoryReadResultBuilder) Build() (HistoryReadResult, error) {
	if b.StatusCode == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'statusCode' not set"))
	}
	if b.ContinuationPoint == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'continuationPoint' not set"))
	}
	if b.HistoryData == nil {
		if b.err == nil {
			b.err = new(utils.MultiError)
		}
		b.err.Append(errors.New("mandatory field 'historyData' not set"))
	}
	if b.err != nil {
		return nil, errors.Wrap(b.err, "error occurred during build")
	}
	return b._HistoryReadResult.deepCopy(), nil
}

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

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

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

func (b *_HistoryReadResultBuilder) DeepCopy() any {
	_copy := b.CreateHistoryReadResultBuilder().(*_HistoryReadResultBuilder)
	if b.err != nil {
		_copy.err = b.err.DeepCopy().(*utils.MultiError)
	}
	return _copy
}

// CreateHistoryReadResultBuilder creates a HistoryReadResultBuilder
func (b *_HistoryReadResult) CreateHistoryReadResultBuilder() HistoryReadResultBuilder {
	if b == nil {
		return NewHistoryReadResultBuilder()
	}
	return &_HistoryReadResultBuilder{_HistoryReadResult: b.deepCopy()}
}

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

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

func (m *_HistoryReadResult) GetExtensionId() int32 {
	return int32(640)
}

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

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

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

func (m *_HistoryReadResult) GetStatusCode() StatusCode {
	return m.StatusCode
}

func (m *_HistoryReadResult) GetContinuationPoint() PascalByteString {
	return m.ContinuationPoint
}

func (m *_HistoryReadResult) GetHistoryData() ExtensionObject {
	return m.HistoryData
}

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

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

func (m *_HistoryReadResult) GetTypeName() string {
	return "HistoryReadResult"
}

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

	// Simple field (statusCode)
	lengthInBits += m.StatusCode.GetLengthInBits(ctx)

	// Simple field (continuationPoint)
	lengthInBits += m.ContinuationPoint.GetLengthInBits(ctx)

	// Simple field (historyData)
	lengthInBits += m.HistoryData.GetLengthInBits(ctx)

	return lengthInBits
}

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

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

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

	continuationPoint, err := ReadSimpleField[PascalByteString](ctx, "continuationPoint", ReadComplex[PascalByteString](PascalByteStringParseWithBuffer, readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'continuationPoint' field"))
	}
	m.ContinuationPoint = continuationPoint

	historyData, err := ReadSimpleField[ExtensionObject](ctx, "historyData", ReadComplex[ExtensionObject](ExtensionObjectParseWithBufferProducer[ExtensionObject]((bool)(bool(true))), readBuffer))
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("Error parsing 'historyData' field"))
	}
	m.HistoryData = historyData

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

	return m, nil
}

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

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

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

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

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

func (m *_HistoryReadResult) IsHistoryReadResult() {}

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

func (m *_HistoryReadResult) deepCopy() *_HistoryReadResult {
	if m == nil {
		return nil
	}
	_HistoryReadResultCopy := &_HistoryReadResult{
		m.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition).deepCopy(),
		utils.DeepCopy[StatusCode](m.StatusCode),
		utils.DeepCopy[PascalByteString](m.ContinuationPoint),
		utils.DeepCopy[ExtensionObject](m.HistoryData),
	}
	_HistoryReadResultCopy.ExtensionObjectDefinitionContract.(*_ExtensionObjectDefinition)._SubType = m
	return _HistoryReadResultCopy
}

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