/*
 * DataSyncSysInfoTasks.c
 *
 *  Created on: Nov 15, 2025
 *      Author: tummalanr
 */

#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <drivers/spinlock.h>
#include <drivers/ipc_notify.h>
#include "FreeRTOS.h"
#include "event_groups.h"
#include "queue.h"

#include "AppGlobal.h"
#include "AppExterns.h"
#include "BoardInitExtern.h"
#include "CIPCoreDataSynchGlobal.h"
#include "ShmDataSyncExterns.h"
#include "CIPCoreExterns.h"






/*!
 *  <!-- Description: -->
 *
 *  \brief
 *
 *   SystemInfo Acquire Shared Memory Lock for Processing IPC System Info  Messages/Data
 *
 *  <!-- Parameters and return values: -->
 *  \param[in] :None
 *  \return    :
 *              AppRET_T  : AppRET_OK on Success or Error
 */
static AppRET_T sysinfo_sharemem_lock(void)
{
    int32_t     status;
    int32_t     sempstatus;
    uint32_t    timeout = SPINLOCK_GET_TIMEOUT;

    /* Take local mutex to protect against multi-thread from same core */
    sempstatus = SemaphoreP_pend(&System_Info_mutexObj, 10u);
    if(sempstatus != SystemP_SUCCESS) {
           return AppGetSHMLockErr;
    }

    /* Spin till lock is acquired or timeout.*/
    for(;;)
    {
      status = Spinlock_lock(spinlockBaseAddr, SPINLOCKNO_SYSTEM_INFO);
      if(status == SPINLOCK_LOCK_STATUS_FREE) {
          break;  /* Free and taken */
      }

      timeout--;
      if(timeout == 0u) {
              break;
      }

      //vTaskDelay( 1u );
      __asm__ volatile ("nop"); /* Prevent compiler from optimizing away the loop.*/

    }/*for(;;)*/
    if(timeout == 0u) {
      return AppGetSHMLockTimeOutErr;
    }

    return AppRET_OK;
}

/*!
 *  <!-- Description: -->
 *
 *  \brief
 *
 *   IO Modules Release Cyclic Shared Memory Lock
 *
 *  <!-- Parameters and return values: -->
 *  \param[in] : None
 *  \return    : None
 */
static void sysinfo_sharemem_unlock(void)
{
    /* Free the aquired lock and release local mutex.*/
    Spinlock_unlock(spinlockBaseAddr, SPINLOCKNO_SYSTEM_INFO);
    SemaphoreP_post(&System_Info_mutexObj);

    return;
}


/*!
 *  <!-- Description: -->
 *
 *  \brief
 *
 *   System Info Data Sync Req/Resp Task From CIP Core
 *
 *  <!-- Parameters and return values: -->
 *  \param[in] : * pArgs_p  Not Used
 *  \return    : None
 */
void APP_SystemInfoTask(void* pArgs_p)
{
        AppRET_T sts = 0;
        EventBits_t uxBits;


        #ifdef Debug_Verbose
            DebugP_log("[[CAN CORE] - %s [%" PRId64 " ms]\r\n",__func__,(ClockP_getTimeUsec()/1000u));
        #endif
        /* wait for a resource to be available Wait for lss to complete.*/
        for(;;)
        {
            /* Wait a maximum of 100ms for either bit 0 or bit 1 to be set within the event group. Clear the bits before exiting.*/
            uxBits = xEventGroupWaitBits(
                                        xAppStatusEventGroup,                                           /* The event group being tested. */
                                        AppStsEvntGrpCIPSyncomplete_BIT, /* The bits within the event group to wait for. */
                                        pdFALSE,                                                        /* BIT_0 & BIT_4 should be cleared before returning. */
                                        pdTRUE,                                                         /*  wait for all bits */
                                        portMAX_DELAY );                                                /* Wait a maximum of 100ms for either bit to be set. */

            /*if( ( uxBits & 0x03) ==  (AppStsEvntGrpLSSComplete_BIT | AppStsEvntGrpCIPSyncomplete_BIT) )*/
            if( uxBits != 0x00u ) {
                    break;
            }
        }//for(;;)

        #ifdef Debug_Verbose
            DebugP_log("[[CAN CORE] - %s  uxBits[%#x][%" PRId64 " ms]\r\n",__func__,uxBits,(ClockP_getTimeUsec()/1000u));
        #endif
//
////        vTaskDelay(200u );
//        for(uint8_t j=0; j < 3; j++)
//        {
//             sts = sysinfo_sharemem_lock();
//             if(sts == 0)
//             {
//                 system_discovery_status.ModuleDiscoveryStatus = 0x10u;
//
//
//                 sysinfo_sharemem_unlock();
//
//                 if(system_discovery_status.ModuleDiscoveryStatus == ModuleDiscovery_Success) {
//                         break;
//                 }
//             }
//        }


        /*IPC Notify to CIP core IO modules /PZ Modules Board Id are updatednotify the CIP core IO Discovery Type i.e Board Ids are ready*/
//        if(CIP_Synch_Done) {
//            uint32_t     MsgVal = MODULEDISCOVERYFINISH_NOTIFYID | SYSCONFIGSTS_RD_NOTIFY_ID;
//            int32_t sts = IpcNotify_sendMsg(CSL_CORE_ID_R5FSS0_0, SysStatusConfig_IPC_ClientId, MsgVal, 1);
//
//            #ifdef Debug_Verbose
//                 DebugP_log("[[CAN CORE] - %s  IpcNotify_sendMsg(CSL_CORE_ID_R5FSS0_0, SysStatusConfig_IPC_ClientId, MsgVal, 1); sts[%#x][%" PRId64 " ms]\r\n",__func__,sts,(ClockP_getTimeUsec()/1000u));
//             #endif
//
//        }


            vTaskDelay(500u );

            for(;;) {
                /*IPC Notify to CIP core IO modules /PZ Modules Board Id are updatednotify the CIP core IO Discovery Type i.e Board Ids are ready*/
                       if(CIP_Synch_Done) {
                           uint32_t     MsgVal = MODULEDISCOVERYFINISH_NOTIFYID | SYSCONFIGSTS_RD_NOTIFY_ID;
                           int32_t sts = IpcNotify_sendMsg(CSL_CORE_ID_R5FSS0_0, SysStatusConfig_IPC_ClientId, MsgVal, 1);

                            #ifdef Debug_Verbose
                                DebugP_log("[[CAN CORE] - %s  IpcNotify_sendMsg(CSL_CORE_ID_R5FSS0_0, SysStatusConfig_IPC_ClientId, MsgVal, 1); msgValue : 0x800100 sts[%#x][%" PRId64 " ms]\r\n",__func__,sts,(ClockP_getTimeUsec()/1000u));
                            #endif
                       }

                vTaskDelay(5000u );
            }

        vTaskDelete( gSystemInfoTask );
}
