/*
 * 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
 *
 *   http://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 (
	"github.com/apache/plc4x/plc4go/internal/plc4go/spi/utils"
	"github.com/pkg/errors"
)

// Code generated by code-generation. DO NOT EDIT.

// The data-structure of this message
type ModbusPDU struct {
	Child IModbusPDUChild
}

// The corresponding interface
type IModbusPDU interface {
	ErrorFlag() bool
	FunctionFlag() uint8
	Response() bool
	LengthInBytes() uint16
	LengthInBits() uint16
	Serialize(writeBuffer utils.WriteBuffer) error
}

type IModbusPDUParent interface {
	SerializeParent(writeBuffer utils.WriteBuffer, child IModbusPDU, serializeChildFunction func() error) error
	GetTypeName() string
}

type IModbusPDUChild interface {
	Serialize(writeBuffer utils.WriteBuffer) error
	InitializeParent(parent *ModbusPDU)
	GetTypeName() string
	IModbusPDU
}

func NewModbusPDU() *ModbusPDU {
	return &ModbusPDU{}
}

func CastModbusPDU(structType interface{}) *ModbusPDU {
	castFunc := func(typ interface{}) *ModbusPDU {
		if casted, ok := typ.(ModbusPDU); ok {
			return &casted
		}
		if casted, ok := typ.(*ModbusPDU); ok {
			return casted
		}
		return nil
	}
	return castFunc(structType)
}

func (m *ModbusPDU) GetTypeName() string {
	return "ModbusPDU"
}

func (m *ModbusPDU) LengthInBits() uint16 {
	return m.LengthInBitsConditional(false)
}

func (m *ModbusPDU) LengthInBitsConditional(lastItem bool) uint16 {
	return m.Child.LengthInBits()
}

func (m *ModbusPDU) ParentLengthInBits() uint16 {
	lengthInBits := uint16(0)
	// Discriminator Field (errorFlag)
	lengthInBits += 1
	// Discriminator Field (functionFlag)
	lengthInBits += 7

	return lengthInBits
}

func (m *ModbusPDU) LengthInBytes() uint16 {
	return m.LengthInBits() / 8
}

func ModbusPDUParse(readBuffer utils.ReadBuffer, response bool) (*ModbusPDU, error) {
	if pullErr := readBuffer.PullContext("ModbusPDU"); pullErr != nil {
		return nil, pullErr
	}

	// Discriminator Field (errorFlag) (Used as input to a switch field)
	errorFlag, _errorFlagErr := readBuffer.ReadBit("errorFlag")
	if _errorFlagErr != nil {
		return nil, errors.Wrap(_errorFlagErr, "Error parsing 'errorFlag' field")
	}

	// Discriminator Field (functionFlag) (Used as input to a switch field)
	functionFlag, _functionFlagErr := readBuffer.ReadUint8("functionFlag", 7)
	if _functionFlagErr != nil {
		return nil, errors.Wrap(_functionFlagErr, "Error parsing 'functionFlag' field")
	}

	// Switch Field (Depending on the discriminator values, passes the instantiation to a sub-type)
	var _parent *ModbusPDU
	var typeSwitchError error
	switch {
	case errorFlag == true: // ModbusPDUError
		_parent, typeSwitchError = ModbusPDUErrorParse(readBuffer)
	case errorFlag == false && functionFlag == 0x02 && response == false: // ModbusPDUReadDiscreteInputsRequest
		_parent, typeSwitchError = ModbusPDUReadDiscreteInputsRequestParse(readBuffer)
	case errorFlag == false && functionFlag == 0x02 && response == true: // ModbusPDUReadDiscreteInputsResponse
		_parent, typeSwitchError = ModbusPDUReadDiscreteInputsResponseParse(readBuffer)
	case errorFlag == false && functionFlag == 0x01 && response == false: // ModbusPDUReadCoilsRequest
		_parent, typeSwitchError = ModbusPDUReadCoilsRequestParse(readBuffer)
	case errorFlag == false && functionFlag == 0x01 && response == true: // ModbusPDUReadCoilsResponse
		_parent, typeSwitchError = ModbusPDUReadCoilsResponseParse(readBuffer)
	case errorFlag == false && functionFlag == 0x05 && response == false: // ModbusPDUWriteSingleCoilRequest
		_parent, typeSwitchError = ModbusPDUWriteSingleCoilRequestParse(readBuffer)
	case errorFlag == false && functionFlag == 0x05 && response == true: // ModbusPDUWriteSingleCoilResponse
		_parent, typeSwitchError = ModbusPDUWriteSingleCoilResponseParse(readBuffer)
	case errorFlag == false && functionFlag == 0x0F && response == false: // ModbusPDUWriteMultipleCoilsRequest
		_parent, typeSwitchError = ModbusPDUWriteMultipleCoilsRequestParse(readBuffer)
	case errorFlag == false && functionFlag == 0x0F && response == true: // ModbusPDUWriteMultipleCoilsResponse
		_parent, typeSwitchError = ModbusPDUWriteMultipleCoilsResponseParse(readBuffer)
	case errorFlag == false && functionFlag == 0x04 && response == false: // ModbusPDUReadInputRegistersRequest
		_parent, typeSwitchError = ModbusPDUReadInputRegistersRequestParse(readBuffer)
	case errorFlag == false && functionFlag == 0x04 && response == true: // ModbusPDUReadInputRegistersResponse
		_parent, typeSwitchError = ModbusPDUReadInputRegistersResponseParse(readBuffer)
	case errorFlag == false && functionFlag == 0x03 && response == false: // ModbusPDUReadHoldingRegistersRequest
		_parent, typeSwitchError = ModbusPDUReadHoldingRegistersRequestParse(readBuffer)
	case errorFlag == false && functionFlag == 0x03 && response == true: // ModbusPDUReadHoldingRegistersResponse
		_parent, typeSwitchError = ModbusPDUReadHoldingRegistersResponseParse(readBuffer)
	case errorFlag == false && functionFlag == 0x06 && response == false: // ModbusPDUWriteSingleRegisterRequest
		_parent, typeSwitchError = ModbusPDUWriteSingleRegisterRequestParse(readBuffer)
	case errorFlag == false && functionFlag == 0x06 && response == true: // ModbusPDUWriteSingleRegisterResponse
		_parent, typeSwitchError = ModbusPDUWriteSingleRegisterResponseParse(readBuffer)
	case errorFlag == false && functionFlag == 0x10 && response == false: // ModbusPDUWriteMultipleHoldingRegistersRequest
		_parent, typeSwitchError = ModbusPDUWriteMultipleHoldingRegistersRequestParse(readBuffer)
	case errorFlag == false && functionFlag == 0x10 && response == true: // ModbusPDUWriteMultipleHoldingRegistersResponse
		_parent, typeSwitchError = ModbusPDUWriteMultipleHoldingRegistersResponseParse(readBuffer)
	case errorFlag == false && functionFlag == 0x17 && response == false: // ModbusPDUReadWriteMultipleHoldingRegistersRequest
		_parent, typeSwitchError = ModbusPDUReadWriteMultipleHoldingRegistersRequestParse(readBuffer)
	case errorFlag == false && functionFlag == 0x17 && response == true: // ModbusPDUReadWriteMultipleHoldingRegistersResponse
		_parent, typeSwitchError = ModbusPDUReadWriteMultipleHoldingRegistersResponseParse(readBuffer)
	case errorFlag == false && functionFlag == 0x16 && response == false: // ModbusPDUMaskWriteHoldingRegisterRequest
		_parent, typeSwitchError = ModbusPDUMaskWriteHoldingRegisterRequestParse(readBuffer)
	case errorFlag == false && functionFlag == 0x16 && response == true: // ModbusPDUMaskWriteHoldingRegisterResponse
		_parent, typeSwitchError = ModbusPDUMaskWriteHoldingRegisterResponseParse(readBuffer)
	case errorFlag == false && functionFlag == 0x18 && response == false: // ModbusPDUReadFifoQueueRequest
		_parent, typeSwitchError = ModbusPDUReadFifoQueueRequestParse(readBuffer)
	case errorFlag == false && functionFlag == 0x18 && response == true: // ModbusPDUReadFifoQueueResponse
		_parent, typeSwitchError = ModbusPDUReadFifoQueueResponseParse(readBuffer)
	case errorFlag == false && functionFlag == 0x14 && response == false: // ModbusPDUReadFileRecordRequest
		_parent, typeSwitchError = ModbusPDUReadFileRecordRequestParse(readBuffer)
	case errorFlag == false && functionFlag == 0x14 && response == true: // ModbusPDUReadFileRecordResponse
		_parent, typeSwitchError = ModbusPDUReadFileRecordResponseParse(readBuffer)
	case errorFlag == false && functionFlag == 0x15 && response == false: // ModbusPDUWriteFileRecordRequest
		_parent, typeSwitchError = ModbusPDUWriteFileRecordRequestParse(readBuffer)
	case errorFlag == false && functionFlag == 0x15 && response == true: // ModbusPDUWriteFileRecordResponse
		_parent, typeSwitchError = ModbusPDUWriteFileRecordResponseParse(readBuffer)
	case errorFlag == false && functionFlag == 0x07 && response == false: // ModbusPDUReadExceptionStatusRequest
		_parent, typeSwitchError = ModbusPDUReadExceptionStatusRequestParse(readBuffer)
	case errorFlag == false && functionFlag == 0x07 && response == true: // ModbusPDUReadExceptionStatusResponse
		_parent, typeSwitchError = ModbusPDUReadExceptionStatusResponseParse(readBuffer)
	case errorFlag == false && functionFlag == 0x08 && response == false: // ModbusPDUDiagnosticRequest
		_parent, typeSwitchError = ModbusPDUDiagnosticRequestParse(readBuffer)
	case errorFlag == false && functionFlag == 0x08 && response == true: // ModbusPDUDiagnosticResponse
		_parent, typeSwitchError = ModbusPDUDiagnosticResponseParse(readBuffer)
	case errorFlag == false && functionFlag == 0x0B && response == false: // ModbusPDUGetComEventCounterRequest
		_parent, typeSwitchError = ModbusPDUGetComEventCounterRequestParse(readBuffer)
	case errorFlag == false && functionFlag == 0x0B && response == true: // ModbusPDUGetComEventCounterResponse
		_parent, typeSwitchError = ModbusPDUGetComEventCounterResponseParse(readBuffer)
	case errorFlag == false && functionFlag == 0x0C && response == false: // ModbusPDUGetComEventLogRequest
		_parent, typeSwitchError = ModbusPDUGetComEventLogRequestParse(readBuffer)
	case errorFlag == false && functionFlag == 0x0C && response == true: // ModbusPDUGetComEventLogResponse
		_parent, typeSwitchError = ModbusPDUGetComEventLogResponseParse(readBuffer)
	case errorFlag == false && functionFlag == 0x11 && response == false: // ModbusPDUReportServerIdRequest
		_parent, typeSwitchError = ModbusPDUReportServerIdRequestParse(readBuffer)
	case errorFlag == false && functionFlag == 0x11 && response == true: // ModbusPDUReportServerIdResponse
		_parent, typeSwitchError = ModbusPDUReportServerIdResponseParse(readBuffer)
	case errorFlag == false && functionFlag == 0x2B && response == false: // ModbusPDUReadDeviceIdentificationRequest
		_parent, typeSwitchError = ModbusPDUReadDeviceIdentificationRequestParse(readBuffer)
	case errorFlag == false && functionFlag == 0x2B && response == true: // ModbusPDUReadDeviceIdentificationResponse
		_parent, typeSwitchError = ModbusPDUReadDeviceIdentificationResponseParse(readBuffer)
	default:
		// TODO: return actual type
		typeSwitchError = errors.New("Unmapped type")
	}
	if typeSwitchError != nil {
		return nil, errors.Wrap(typeSwitchError, "Error parsing sub-type for type-switch.")
	}

	if closeErr := readBuffer.CloseContext("ModbusPDU"); closeErr != nil {
		return nil, closeErr
	}

	// Finish initializing
	_parent.Child.InitializeParent(_parent)
	return _parent, nil
}

func (m *ModbusPDU) Serialize(writeBuffer utils.WriteBuffer) error {
	return m.Child.Serialize(writeBuffer)
}

func (m *ModbusPDU) SerializeParent(writeBuffer utils.WriteBuffer, child IModbusPDU, serializeChildFunction func() error) error {
	if pushErr := writeBuffer.PushContext("ModbusPDU"); pushErr != nil {
		return pushErr
	}

	// Discriminator Field (errorFlag) (Used as input to a switch field)
	errorFlag := bool(child.ErrorFlag())
	_errorFlagErr := writeBuffer.WriteBit("errorFlag", (errorFlag))

	if _errorFlagErr != nil {
		return errors.Wrap(_errorFlagErr, "Error serializing 'errorFlag' field")
	}

	// Discriminator Field (functionFlag) (Used as input to a switch field)
	functionFlag := uint8(child.FunctionFlag())
	_functionFlagErr := writeBuffer.WriteUint8("functionFlag", 7, (functionFlag))

	if _functionFlagErr != nil {
		return errors.Wrap(_functionFlagErr, "Error serializing 'functionFlag' field")
	}

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

	if popErr := writeBuffer.PopContext("ModbusPDU"); popErr != nil {
		return popErr
	}
	return nil
}

func (m *ModbusPDU) String() string {
	if m == nil {
		return "<nil>"
	}
	buffer := utils.NewBoxedWriteBufferWithOptions(true, true)
	m.Serialize(buffer)
	return buffer.GetBox().String()
}
