/*
 * Copyright 2018-2025 NXP
 * All rights reserved.
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */

#include "board.h"
#include "timer.h"

#include <stdint.h>
#if defined(__ICCARM__) || defined(__ARMCC_VERSION) || defined(__REDLIB__)
#include <time.h>
#else
#include <sys/time.h>
#endif

#include "FreeRTOS.h"
#include "task.h"
#include "fsl_debug_console.h"

/*******************************************************************************
 * Definitions
 ******************************************************************************/

/*! @brief Timer settings */
#define SYSTICK_PRESCALE 1U
#define TICK_PRIORITY 1U

/*******************************************************************************
 * Variables
 ******************************************************************************/
volatile uint32_t msTicks;

/*******************************************************************************
 * Code
 ******************************************************************************/
void TIMER_Init(void)
{

}

int TIMER_GetTimeInUS()
{
    uint64_t us = ((SystemCoreClock / configTICK_RATE_HZ) - SysTick->VAL) / (SystemCoreClock / 1000000);
    us += (uint64_t) xTaskGetTickCount() * portTICK_PERIOD_MS * 1000;
    return us;
}

volatile uint32_t tickCount = 0;  // Records the system Tick count
// Tick Hook function to track system Tick count
void vApplicationTickHook(void)
{
   tickCount++;  // Increment system Tick count on every Tick interrupt
}

// Task to calculate CPU Load
void CPU_LoadMonitor_Task(void *pvParameters)
{
   uint32_t lastIdleTime = 0;
   uint32_t lastTickCount = 0;
   while (1)
   {
       vTaskDelay(pdMS_TO_TICKS(5000)); // Wait for x seconds before calculating CPU Load
       // Get the Idle Task runtime (in CPU cycles)
       uint32_t idleTime = xTaskGetIdleRunTimeCounter() - lastIdleTime;
       uint32_t totalTime = tickCount - lastTickCount;

       // Calculate CPU Load (assuming 1 Tick = 1000 us)
       uint32_t cpuLoad = 100 - ((idleTime * 100) / (totalTime * 1000));
       PRINTF("\r\nCPU Load: %.d%% (Idle Time: %d us, Total Time: %d us)\r\n", cpuLoad, idleTime, totalTime * 1000);

       // Update previous values
       lastIdleTime = xTaskGetIdleRunTimeCounter();
       lastTickCount = tickCount;
   }
}

