/*******************************************************************************
 * @file
 * @brief Core application logic.
 *******************************************************************************
 * # License
 * <b>Copyright 2024 Silicon Laboratories Inc. www.silabs.com</b>
 *******************************************************************************
 *
 * SPDX-License-Identifier: Zlib
 *
 * The licensor of this software is Silicon Laboratories Inc.
 *
 * This software is provided 'as-is', without any express or implied
 * warranty. In no event will the authors be held liable for any damages
 * arising from the use of this software.
 *
 * Permission is granted to anyone to use this software for any purpose,
 * including commercial applications, and to alter it and redistribute it
 * freely, subject to the following restrictions:
 *
 * 1. The origin of this software must not be misrepresented; you must not
 *    claim that you wrote the original software. If you use this software
 *    in a product, an acknowledgment in the product documentation would be
 *    appreciated but is not required.
 * 2. Altered source versions must be plainly marked as such, and must not be
 *    misrepresented as being the original software.
 * 3. This notice may not be removed or altered from any source distribution.
 *
 ******************************************************************************/

// Define module name for Power Manager debuging feature.
#define CURRENT_MODULE_NAME "OPENTHREAD_SAMPLE_APP"

#include <assert.h>
#include <string.h>
#include <openthread-core-config.h>
#include <openthread/config.h>
#include <openthread/error.h>

#include <openthread/cli.h>
#include <openthread/diag.h>
#include <openthread/ip6.h>
#include <openthread/link.h>
#include <openthread/link_raw.h>
#include <openthread/thread.h>
#include <openthread/tasklet.h>

#include "app.h"
#include "openthread-system.h"

#include "reset_util.h"

#include "sl_component_catalog.h"
#include "sl_memory_manager.h"
#ifdef SL_CATALOG_POWER_MANAGER_PRESENT
#include "sl_power_manager.h"
#endif

#ifdef SL_CATALOG_KERNEL_PRESENT
#include "sl_ot_rtos_adaptation.h"
#endif // SL_CATALOG_KERNEL_PRESENT

#if (defined(SL_CATALOG_BTN0_PRESENT) || defined(SL_CATALOG_BTN1_PRESENT))
#include "sl_button.h"
#include "sl_simple_button.h"
#endif

/**
 * This function initializes the CLI app.
 *
 * @param[in]  aInstance  The OpenThread instance structure.
 *
 */
extern void otAppCliInit(otInstance *aInstance);

#if OPENTHREAD_CONFIG_MULTIPLE_INSTANCE_ENABLE && !OPENTHREAD_CONFIG_MULTIPLE_STATIC_INSTANCE_ENABLE
static uint8_t *sOtInstanceBuffer = NULL;
#endif
static otInstance *sInstance      = NULL;
static bool        sButtonPressed = false;
static bool        sStayAwake     = true;
static uint8_t     sWakeupSequenceNumber;

static otError restart_thread_stack(otInstance *aInstance)
{
    otError error = otIp6SetEnabled(aInstance, true);

    otCliOutputFormat("raw-wakeup: IPv6 enable: %s\r\n", otThreadErrorToString(error));

    if (error == OT_ERROR_NONE)
    {
        error = otThreadSetEnabled(aInstance, true);
        otCliOutputFormat("raw-wakeup: Thread enable: %s\r\n", otThreadErrorToString(error));
    }
    return error;
}

/* Send the example IEEE 802.15.4 wakeup frame on channel 11 in raw mode. */
static void raw_receive_done(otInstance *aInstance, otRadioFrame *aFrame, otError aError)
{
    OT_UNUSED_VARIABLE(aInstance);
    if (aError != OT_ERROR_NONE)
    {
        otCliOutputFormat("raw receive: %s\r\n", otThreadErrorToString(aError));
    }
}

static void raw_transmit_done(otInstance *aInstance,
                              otRadioFrame *aFrame,
                              otRadioFrame *aAckFrame,
                              otError aError)
{
    OT_UNUSED_VARIABLE(aInstance);
    otCliOutputFormat("raw transmit done: %s, len=%u channel=%u ack=%s\r\n",
                      otThreadErrorToString(aError), aFrame ? aFrame->mLength : 0,
                      aFrame ? aFrame->mChannel : 0, aAckFrame ? "yes" : "no");
    otError rawDisableError = otLinkRawSetReceiveDone(aInstance, NULL);
    otCliOutputFormat("raw-wakeup: raw disable: %s\r\n", otThreadErrorToString(rawDisableError));
    otError restartError = restart_thread_stack(aInstance);
    otCliOutputFormat("Thread restart: %s\r\n", otThreadErrorToString(restartError));
}

static otError cli_raw_wakeup(void *aContext, uint8_t aArgsLength, char *aArgs[])
{
    otInstance   *instance = (otInstance *)aContext;
    otRadioFrame *txFrame;
    uint8_t      *psdu;
    uint8_t       idx = 0;
    static const uint8_t payload[] = {0xde, 0xad, 0xbe, 0xef};
    otPanId       panId;
    otShortAddress sourceAddress;
    uint8_t       channel;
    otError       error;

    OT_UNUSED_VARIABLE(aArgs);
    if (aArgsLength != 0)
    {
        return OT_ERROR_INVALID_ARGS;
    }

    /* Read the Thread link configuration before taking the stack offline. */
    panId         = otLinkGetPanId(instance);
    sourceAddress = otLinkGetShortAddress(instance);
    channel       = otLinkGetChannel(instance);

    otCliOutputFormat("raw-wakeup: start PANID=0x%04x short=0x%04x channel=%u\r\n",
                      panId, sourceAddress, channel);

    // Disable The thread stack before sending the raw packet
    error = otThreadSetEnabled(instance, false);
    otCliOutputFormat("raw-wakeup: Thread disable: %s\r\n", otThreadErrorToString(error));
    if (error != OT_ERROR_NONE) 
      return error;

    error = otIp6SetEnabled(instance, false);
    otCliOutputFormat("raw-wakeup: IPv6 disable: %s\r\n", otThreadErrorToString(error));
    if (error != OT_ERROR_NONE) 
      goto restore_stack;

    error = otLinkRawSetReceiveDone(instance, raw_receive_done);
    otCliOutputFormat("raw-wakeup: raw enable: %s\r\n", otThreadErrorToString(error));
    if (error != OT_ERROR_NONE) 
      goto restore_stack;

    error = otLinkRawReceive(instance);
    otCliOutputFormat("raw-wakeup: raw receive start: %s\r\n", otThreadErrorToString(error));
    if (error != OT_ERROR_NONE) 
      goto restore_stack;

    txFrame = otLinkRawGetTransmitBuffer(instance);
    if (txFrame == NULL)
    {
        error = OT_ERROR_NO_BUFS;
        goto restore_stack;
    }

    otCliOutputFormat("raw-wakeup: TX buffer acquired\r\n");
    psdu = txFrame->mPsdu;

    /* FCF 0x8861: Data, ACK request, PAN compression, short/short, v0. */
    psdu[idx++] = 0x61;
    psdu[idx++] = 0x88;
    psdu[idx++] = sWakeupSequenceNumber++;
    psdu[idx++] = (uint8_t)(panId & 0xff);
    psdu[idx++] = (uint8_t)(panId >> 8);
    psdu[idx++] = 0x02; /* Destination short address */
    psdu[idx++] = 0x00;
    psdu[idx++] = (uint8_t)(sourceAddress & 0xff);
    psdu[idx++] = (uint8_t)(sourceAddress >> 8);
    memcpy(&psdu[idx], payload, sizeof(payload));
    idx += sizeof(payload);

    txFrame->mLength  = idx + 2; /* Hardware generates the FCS. */
    txFrame->mChannel = channel;
    
    otCliOutputFormat("raw-wakeup: requesting TX len=%u channel=%u\r\n", txFrame->mLength, channel);
    error = otLinkRawTransmit(instance, raw_transmit_done);
    otCliOutputFormat("raw-wakeup: transmit request: %s\r\n", otThreadErrorToString(error));
    if (error != OT_ERROR_NONE)
    {
        goto restore_stack;
    }
    return error;

restore_stack:
    otCliOutputFormat("raw-wakeup: setup failed: %s; disabling raw and restoring stack\r\n",
                      otThreadErrorToString(error));
    otError rawDisableError = otLinkRawSetReceiveDone(instance, NULL);
    otCliOutputFormat("raw-wakeup: raw disable: %s\r\n", otThreadErrorToString(rawDisableError));
    otError restartError = restart_thread_stack(instance);
    otCliOutputFormat("Thread restart after setup error: %s\r\n", otThreadErrorToString(restartError));
    return error;
}

static const otCliCommand sRawWakeupCommand[] = {{"raw-wakeup", cli_raw_wakeup}};

#if (defined(SL_CATALOG_BTN0_PRESENT) || defined(SL_CATALOG_BTN1_PRESENT))
void sl_button_on_change(const sl_button_t *handle)
{
    if (sl_button_get_state(handle) == SL_SIMPLE_BUTTON_PRESSED)
    {
        sButtonPressed = true;
#ifdef SL_CATALOG_KERNEL_PRESENT
        sl_ot_rtos_set_pending_event(SL_OT_RTOS_EVENT_APP);
#endif
        otSysEventSignalPending();
    }
}
#endif

void sl_ot_rtos_application_tick(void)
{
    if (sButtonPressed)
    {
        sButtonPressed = false;
        sStayAwake     = !sStayAwake;
        if (sStayAwake)
        {
#ifdef SL_CATALOG_POWER_MANAGER_PRESENT
            sl_power_manager_add_em_requirement(SL_POWER_MANAGER_EM1);
#endif
        }
        else
        {
#ifdef SL_CATALOG_POWER_MANAGER_PRESENT
            sl_power_manager_remove_em_requirement(SL_POWER_MANAGER_EM1);
#endif
        }
    }
}

/*
 * Provide, if required an "otPlatLog()" function
 */
#if OPENTHREAD_CONFIG_LOG_OUTPUT == OPENTHREAD_CONFIG_LOG_OUTPUT_APP
void otPlatLog(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aFormat, ...)
{
    OT_UNUSED_VARIABLE(aLogLevel);
    OT_UNUSED_VARIABLE(aLogRegion);
    OT_UNUSED_VARIABLE(aFormat);

    va_list ap;
    va_start(ap, aFormat);
    otCliPlatLogv(aLogLevel, aLogRegion, aFormat, ap);
    va_end(ap);
}
#endif

void sl_ot_create_instance(void)
{
#if OPENTHREAD_CONFIG_MULTIPLE_INSTANCE_ENABLE
#if !OPENTHREAD_CONFIG_MULTIPLE_STATIC_INSTANCE_ENABLE
    size_t otInstanceBufferLength = 0;

    // Call to query the buffer size
    (void)otInstanceInit(NULL, &otInstanceBufferLength);

    // Call to allocate the buffer
    sOtInstanceBuffer = (uint8_t *)sl_malloc(otInstanceBufferLength);
    assert(sOtInstanceBuffer);

    // Initialize OpenThread with the buffer
    sInstance = otInstanceInit(sOtInstanceBuffer, &otInstanceBufferLength);
#else
    sInstance = otInstanceInitMultiple(0);
#endif
#else
    sInstance = otInstanceInitSingle();
#endif
    assert(sInstance);
}

void sl_ot_cli_init(void)
{
    otAppCliInit(sInstance);
    (void)otCliSetUserCommands(sRawWakeupCommand,
                               (uint8_t)(sizeof(sRawWakeupCommand) / sizeof(sRawWakeupCommand[0])),
                               sInstance);
}

/******************************************************************************
 * Application Init.
 *****************************************************************************/

void app_init(void)
{
    OT_SETUP_RESET_JUMP(argv);
}

/******************************************************************************
 * Application Process Action.
 *****************************************************************************/
void app_process_action(void)
{
    otTaskletsProcess(sInstance);
    otSysProcessDrivers(sInstance);
}

/******************************************************************************
 * Application Exit.
 *****************************************************************************/
void app_exit(void)
{
    otInstanceFinalize(sInstance);
#if OPENTHREAD_CONFIG_MULTIPLE_INSTANCE_ENABLE && !OPENTHREAD_CONFIG_MULTIPLE_STATIC_INSTANCE_ENABLE
    sl_free(sOtInstanceBuffer);
#endif
    // TO DO : pseudo reset?
}
