/*****************************************************************************/
/**
 * @file service.c
 * @author FanHao (hao_fan_bit_ee@163.com)
 * @brief DF Linklayer service implementation file.
 * @version 0.0
 * @date 2023-05-06
 *
 * @copyright Copyright(c) 2024 Beijing Institute of Technology.\n
 * Lab of Communication and Network
 *
 ******************************************************************************/
/**
 * @addtogroup LinkLayer
 * @{
 */

/**
 * @addtogroup LinkLayer_Service
 * @{
 */
/***************************** Include Files *********************************/
#include <string.h>
#include <stdint.h>
#include "link_layer.h"
#include "link_layer_types.h"
#include "msg_def.h"
#include "error.h"
#include "common.h"
#include "circ_queue.h"
#ifndef EMULATION
#include "../config/app_config.h"
#endif
/************************** Constant Definitions *****************************/
/***************** Macros (Inline Functions) Definitions *********************/
/**************************** Type Definitions *******************************/
/************************** Function Prototypes ******************************/
static int32_t Service_Packing(L2_INST *instPtr, L2_FRAME_TYPE type, uint8_t dstId);
/************************** Variable Definitions *****************************/

static uint8_t testData[L2_PACK_LEN_MAX] =
{
	0x39, 0x85, 0x02, 0xF0, 0xC7, 0x6A, 0xE8, 0xB4, 0xE7, 0xAB, 0xC9, 0xDC, 0x0B, 0x41, 0x42, 0xE0,
	0xED, 0x21, 0x07, 0x62, 0x4E, 0x80, 0xA0, 0xE1, 0xAC, 0x77, 0x9B, 0x1F, 0x48, 0x0B, 0x58, 0xB9,
	0x45, 0xA5, 0x24, 0xEF, 0xF3, 0x71, 0x2E, 0x84, 0x6C, 0x22, 0xB3, 0x05, 0xEB, 0x75, 0xF2, 0x0B,
	0x45, 0x73, 0x01, 0xA8, 0x1E, 0x00, 0x21, 0x3E, 0x03, 0x86, 0x55, 0x59, 0x98, 0x5C, 0x61, 0xA2,
	0xE8, 0x20, 0x0E, 0x7A, 0xD5, 0x72, 0xAF, 0xF4, 0xBC, 0xB3, 0x6F, 0xFE, 0xB3, 0x78, 0x6A, 0x59,
	0x73, 0xBD, 0x97, 0xBE, 0x44, 0xA4, 0x9B, 0x71, 0x11, 0x45, 0x37, 0xFE, 0xB3, 0x71, 0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A8, 0x00, 0x2E, 0x70, 0x73, 0x2F, 0x74, 0xBC, 0x61,
	0x0A, 0x8E, 0xE3, 0x0A, 0x92, 0x82, 0xD2, 0x82, 0xBA, 0xE4, 0x3E, 0x8E, 0xBB, 0xC7, 0xA2, 0x8F,
	0x68, 0xE1, 0x29, 0x34, 0x7C, 0xB4, 0x22, 0xCF, 0x36, 0x8F, 0x9D, 0x63, 0x9D, 0x04, 0x8F, 0x4A,
	0xFB, 0x84, 0xBB, 0x6B, 0x97, 0x2C, 0x15, 0xC9, 0x37, 0x4F, 0x40, 0xD7, 0x47, 0x50, 0x39, 0x97
};

/*****************************************************************************/
/**
 * @brief   Packing Service message
 *
 * @param   instPtr		pointer to linklayer instance
 *          type		message type.
 *          dstId		destination node address.
 *
 * @return	EPARAM
 * 			SUCCESS
 *
 ******************************************************************************/
static int32_t Service_Packing(L2_INST *instPtr, L2_FRAME_TYPE type, uint8_t dstId)
{
#ifndef DATALINK_ENABLE_BERTEST
	ASSERT(instPtr != NULL);
	int32_t Status;
	uint32_t dataChunk;
	uint8_t *buff = instPtr->sendPktData;

	// Common section of link layer package
	dataChunk = L2_GetNextFrameNum(instPtr);
	L2_FrameInsertChunk(buff, L2_MSG_FRAME_NUM, L2_MSG_FRAME_NUM_LEN, &dataChunk);
	dataChunk = L2_GetNextSlotNum(instPtr);
	L2_FrameInsertChunk(buff, L2_MSG_SLOT_NUM, L2_MSG_SLOT_NUM_LEN, &dataChunk);
	dataChunk = L2_GetNodeId(instPtr);
	L2_FrameInsertChunk(buff, L2_MSG_SRC_ID, L2_MSG_SRC_ID_LEN, &dataChunk);
	dataChunk = dstId;
	L2_FrameInsertChunk(buff, L2_MSG_DST_ID, L2_MSG_DST_ID_LEN, &dataChunk);
	switch (type)
	{
	case L2_SVC_FRAME:
	{
		dataChunk = L2_SVC_FRAME;
		L2_FrameInsertChunk(buff, L2_MSG_TYPE, L2_MSG_TYPE_LEN, &dataChunk);

		SysMonitor_GetSysinfo(&(instPtr->sysInfo));
		// insert position and speed info
		L2_FrameInsertChunk(buff, L2_MSG_SVC_SRC_POSX, L2_MSG_SVC_SRC_POSX_LEN, &(instPtr->sysInfo.posX));
		L2_FrameInsertChunk(buff, L2_MSG_SVC_SRC_POSY, L2_MSG_SVC_SRC_POSY_LEN, &(instPtr->sysInfo.posY));
		L2_FrameInsertChunk(buff, L2_MSG_SVC_SRC_POSZ, L2_MSG_SVC_SRC_POSZ_LEN, &(instPtr->sysInfo.posZ));
		L2_FrameInsertChunk(buff, L2_MSG_SVC_SRC_SPEEDX, L2_MSG_SVC_SRC_SPEEDX_LEN, &(instPtr->sysInfo.vX));
		L2_FrameInsertChunk(buff, L2_MSG_SVC_SRC_SPEEDY, L2_MSG_SVC_SRC_SPEEDY_LEN, &(instPtr->sysInfo.vY));
		L2_FrameInsertChunk(buff, L2_MSG_SVC_SRC_SPEEDZ, L2_MSG_SVC_SRC_SPEEDZ_LEN, &(instPtr->sysInfo.vZ));

		uint32_t dataId;
		if (L2_GetNodeType(instPtr) == L2_NODE_HEAD)
		{
			SysMonitor_GetSendPayload(buff + L2_MSG_SVC_PAYLOAD, &dataId, PAYLOAD_LEN_FLJ_TX);
		}
		else
		{
			SysMonitor_GetSendPayload(buff + L2_MSG_SVC_PAYLOAD, &dataId, PAYLOAD_LEN_LJ_TX);
		}

		L2_FrameInsertChunk(buff, L2_MSG_SVC_PAYLOAD_ID, L2_MSG_SVC_PAYLOAD_ID_LEN, &dataId);
		if (dataId == DATA_ID_NONE)
		{
			L2_FrameInsertChunk(buff, L2_MSG_SVC_PAYLOAD, L2_MSG_SVC_PAYLOAD_LEN, testData);
		}

		Status = L2_CrcAppend(buff, L2_SVC_PACK_LEN - L2_MSG_SVC_CRC_LEN, L2_MSG_SVC_CRC, L2_CRC16_1021);
		if (Status != SUCCESS)
		{
			DBG_ERROR("Fail to append CRC...\n");
			return Status;
		}

		memcpy(instPtr->log.txLog.data, buff, L2_SVC_PACK_LEN);
		instPtr->log.txLog.dataId = dataId;
		break;
	}
	default:
	{
		DBG_ERROR("Unexpected frame type: %" PRIu8 ".\n", type);
		return EPARAM;
		break;
	}
	}
	return SUCCESS;
#else
	DBG_ERROR("Unexpected call of Service_Packing in BER test mode.\n");
	return EUNEXP;
#endif
}

/*****************************************************************************/
/**
 * @brief   Handle service received packet. Send data up to MPC
 *
 * @param   msg A point32_ter the the message frame.
 *
 * @return  SUCCESS message has been successfully handled.
 *          other       error occurred.
 *
 ******************************************************************************/
int32_t L2_Service_PktHandler(L2_INST *instPtr, uint8_t *msg)
{
	ASSERT(instPtr != NULL);
	ASSERT(msg != NULL);
	int32_t Status;
#ifndef DATALINK_ENABLE_BERTEST
	L2_FRAME_TYPE frameType = L2_NONE_FRAME;
	L2_FrameGetChunk(msg, L2_MSG_TYPE, L2_MSG_TYPE_LEN, &frameType);
	switch (frameType)
	{
	case L2_SVC_FRAME:
	{
		uint8_t nodeId;
		L2_FrameGetChunk(msg, L2_MSG_SRC_ID, L2_MSG_SRC_ID_LEN, &nodeId);
		NODE_ENTRY *node;
		node = L2_GetNodeById(instPtr->nodeList, nodeId);
		if (node == NULL)
		{
			node = L2_AppendNode(instPtr->nodeList, nodeId, L2_NODE_MEMBER);
			if (node == NULL)
			{
				DBG_ERROR("Failed to append new node [id: %" PRIu8 "]", nodeId);
				Status = ENOMEM;
				break;
			}
		}

		// Update node info.
		float nodePos;
		L2_FrameGetChunk(msg, L2_MSG_SVC_SRC_POSX, L2_MSG_SVC_SRC_POSX_LEN, &nodePos);
		node->nodeInfo.pos.x = (double)nodePos;
		L2_FrameGetChunk(msg, L2_MSG_SVC_SRC_POSY, L2_MSG_SVC_SRC_POSY_LEN, &nodePos);
		node->nodeInfo.pos.y = (double)nodePos;
		L2_FrameGetChunk(msg, L2_MSG_SVC_SRC_POSZ, L2_MSG_SVC_SRC_POSZ_LEN, &nodePos);
		node->nodeInfo.pos.z = (double)nodePos;
		float nodeSpeed;
		L2_FrameGetChunk(msg, L2_MSG_SVC_SRC_SPEEDX, L2_MSG_SVC_SRC_SPEEDX_LEN, &nodeSpeed);
		node->nodeInfo.speed.x = (double)nodePos;
		L2_FrameGetChunk(msg, L2_MSG_SVC_SRC_SPEEDY, L2_MSG_SVC_SRC_SPEEDY_LEN, &nodeSpeed);
		node->nodeInfo.speed.y = (double)nodePos;
		L2_FrameGetChunk(msg, L2_MSG_SVC_SRC_SPEEDZ, L2_MSG_SVC_SRC_SPEEDZ_LEN, &nodeSpeed);
		node->nodeInfo.speed.z = (double)nodePos;

		// Reset node ttl
		node->ttlCnt = 0;

		// Calculate time deviation
		uint32_t frameNum, slotNum = 0;
		L2_FrameGetChunk(msg, L2_MSG_FRAME_NUM, L2_MSG_FRAME_NUM_LEN, &frameNum);
		L2_FrameGetChunk(msg, L2_MSG_SLOT_NUM, L2_MSG_SLOT_NUM_LEN, &slotNum);
		Status = L2_GetTimeDeviation(instPtr, frameNum, slotNum, true, &(instPtr->log.timeDev));
		if (Status != SUCCESS)
		{
			DBG_ERROR("Failed to compute time deviation.\n")
			break;
		}

		uint32_t dataId;
		L2_FrameGetChunk(msg, L2_MSG_SVC_PAYLOAD_ID, L2_MSG_SVC_PAYLOAD_ID_LEN, &dataId);

		if (L2_GetNodeType(instPtr) == L2_NODE_HEAD)
		{
			SysMonitor_UpdateRecvPayload(msg + L2_MSG_SVC_PAYLOAD, dataId, PAYLOAD_LEN_FLJ_RX);
		}
		else
		{
			SysMonitor_UpdateRecvPayload(msg + L2_MSG_SVC_PAYLOAD, dataId, PAYLOAD_LEN_LJ_RX);
		}

		// Logging
		memcpy(instPtr->log.rxLog.data, msg, L2_SVC_PACK_LEN);
		instPtr->log.rxLog.dataId = dataId;
		instPtr->serviceFSM->rxdCnt++;

#ifdef DATALINK_ENABLE_AUTOTIMESYNC
		// Implement a auto time sync.
		if (L2_GetNodeType(instPtr) != L2_NODE_HEAD)
		{
			// Time sync.
			L2_TimeAdjust(instPtr, &(instPtr->log.timeDev));
		}
#endif
		break;
	}
	default:
		DBG_ERROR("Unsupported frame type: %" PRIu8 ".\n", frameType);
		break;
	}
	return Status;
#else
	uint32_t errorBits = 0;
	for (int i = 0; i < L2_SVC_PACK_LEN; i++)
	{
		errorBits += count_ones(msg[i] ^ testData[i]);
	}

	instPtr->serviceFSM->bitError += errorBits;
	instPtr->serviceFSM->bitTotal += L2_SVC_PACK_LEN * 8;

	// Calculate time deviation
	uint32_t frameNum, slotNum = 0;
	L2_FrameGetChunk(msg, L2_MSG_FRAME_NUM, L2_MSG_FRAME_NUM_LEN, &frameNum);
	L2_FrameGetChunk(msg, L2_MSG_SLOT_NUM, L2_MSG_SLOT_NUM_LEN, &slotNum);
	Status = L2_GetTimeDeviation(instPtr, frameNum, slotNum, true, &(instPtr->log.timeDev));
	if (Status != SUCCESS)
	{
		DBG_ERROR("Failed to compute time deviation.\n")
		return Status;
	}
	// Implement a auto time sync.
	if (L2_GetNodeType(instPtr) != L2_NODE_HEAD)
	{
		// Time sync.
		L2_TimeAdjust(instPtr, &(instPtr->log.timeDev));
	}
	return SUCCESS;
#endif
}

/*****************************************************************************/
/**
 * @brief   Initialize service net FSM
 *
 * @param   serviceFSM  A pointer to service FSM instance.
 *
 * @return  SUCCESS Initialize successfully.
 *          Other       Initialize failed.
 *
 ******************************************************************************/
int32_t L2_Service_Init(L2_SVC_FSM **svcFSMPtr)
{
	ASSERT(svcFSMPtr != NULL);
	*svcFSMPtr = (L2_SVC_FSM *)malloc(sizeof(L2_SVC_FSM));
	if (*svcFSMPtr == NULL)
	{
		return ENOMEM;
	}
	L2_Service_Reset(*svcFSMPtr);
	return SUCCESS;
}

/*****************************************************************************/
/**
 * @brief  Reset ServiceNet FSM
 *
 * @param   scanFsmPtr a pointer to service net finite state machine
 *
 * @return  NONE
 *
 ******************************************************************************/
void L2_Service_Reset(L2_SVC_FSM *svcFSMPtr)
{
	ASSERT(svcFSMPtr != NULL);
	svcFSMPtr->txCnt = 0;
	svcFSMPtr->rxCnt = 0;
	svcFSMPtr->rxdCnt = 0;
#ifdef DATALINK_ENABLE_BERTEST
	svcFSMPtr->bitTotal = 0;
	svcFSMPtr->bitError = 0;
	svcFSMPtr->lossRate = 0;
	svcFSMPtr->errorRate = 0;
#endif
}

/*****************************************************************************/
/**
 * @brief  Destroy ServiceNet FSM, free memory
 *
 * @param   scanFsmPtr a pointer to service net finite state machine
 *
 * @return  NONE
 *
 ******************************************************************************/
void L2_Service_Destroy(L2_SVC_FSM *serviceFSM)
{
	free(serviceFSM);
}

/*****************************************************************************/
/**
 * @brief   Service FSM Routine.
 *
 * @param   instPtr
 * @param   schedEntry
 *
 * @return  Slot has been used.
 *
 ******************************************************************************/
int32_t L2_Service_Routine(L2_INST *instPtr, const L2_RTNE_TABLE_ENTRY *rtneEntry)
{
	ASSERT(instPtr != NULL);
	DBG_INFO("-------- ServiceNet Routine --------\n");

	if (rtneEntry->slotSeq != 0)
	{
		return SUCCESS; // skip
	}

	PHY_INST *phyRef = instPtr->config.phyInstPtr;
	L2_SVC_FSM *svcFSMPtr = instPtr->serviceFSM;
	L2_TOR_TYPE torState;
	const NODE_ENTRY *commNode;
	if (rtneEntry->src == L2_GetNodeId(instPtr))
	{
		torState = L2_TOR_TX;
		commNode = L2_GetNodeById(instPtr->nodeList, rtneEntry->dst);
	}
	else if (rtneEntry->dst == L2_GetNodeId(instPtr))
	{
		torState = L2_TOR_RX;
		commNode = L2_GetNodeById(instPtr->nodeList, rtneEntry->src);
	}
	else
	{
		torState = L2_TOR_SUSPEND;
	}

	// Setup antenna beam
	if (L2_GetNodeType(instPtr) != L2_NODE_HEAD && commNode != NULL)
	{
		Phy_SetBeamWidth(phyRef, PHY_ANT_BEAM_16);
		Phy_SetBeamNo(phyRef, commNode->nodeInfo.beamNo, PHY_ANT_BEAM_16);
		instPtr->log.lastBeamWidth = PHY_ANT_BEAM_16;
	}
	else
	{
		Phy_SetBeamWidth(phyRef, PHY_ANT_BEAM_120);
		instPtr->log.lastBeamWidth = PHY_ANT_BEAM_120;
	}

	switch (rtneEntry->slotType)
	{
	case L2_SLOT_SERVICE:
		if (torState == L2_TOR_TX)
		{
			svcFSMPtr->txCnt++;
#ifndef DATALINK_ENABLE_BERTEST
			// Packing service data
			Service_Packing(instPtr, L2_SVC_FRAME, rtneEntry->dst);
#else
			memcpy(instPtr->sendPktData, testData, L2_SVC_PACK_LEN);
#endif
		}
		else
		{
			svcFSMPtr->rxCnt++;
		}
		L2_SetupNextSlot(instPtr, torState, L2_SVC_FRAME);
		break;
	default:
		DBG_ERROR("UNKNOWN slot type [%" PRIu8 "].\n", rtneEntry->slotType);
		return FAILURE;
	}
#ifdef DATALINK_ENABLE_BERTEST
	uint32_t pktLoss;
	pktLoss = svcFSMPtr->rxCnt - svcFSMPtr->rxdCnt;
	svcFSMPtr->lossRate = (svcFSMPtr->rxCnt == 0) ? 0 : (double)pktLoss / (double)svcFSMPtr->rxCnt;
	svcFSMPtr->errorRate = (svcFSMPtr->bitTotal == 0) ? 0 : (double)svcFSMPtr->bitError / (double)svcFSMPtr->bitTotal;
	DBG_PRINT("Packet Loss Rate -- Total: %lu, Loss: %lu.\n", instPtr->log.svcRxCnt, pktLoss);
	DBG_PRINT("Bit Error Rate -- Total:%lu, Error:%lu.\n", svcFSMPtr->bitTotal, svcFSMPtr->bitError);
#endif
	return SUCCESS;
}

/** @} LinkLayer_Service*/
/** @} LinkLayer*/