/*
* Copyright (c) 2023-2028, SpaceTouch Inc.
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2023-04-18 dongx the first version
*/

#include <stdio.h>
#include <string.h>
#include "platform.h"
//#include <hal_mem.h>
#include <hal_wdt.h>
#include <hal_log.h>
#include <hal_common.h>


//#include <interrupt.h>



void hal_watchdog_init(void)
{
    DEV_RMU->WDOG |= WDOG_CLR;
    DEV_RMU->WDOG &= ~WDOG_TIME_MASK;
    DEV_RMU->WDOG |= WDOG_TIME_2s;
    DEV_RMU->WDOG &= ~WDOG_DEFER_MASK;
    DEV_RMU->WDOG |= WDOG_DEFER_125ms;
    DEV_RMU->WDOG |= WDOG_DEFER_EN;
    DEV_RMU->WDOG |= WDOG_RESET_EN;
    DEV_RMU->WDOG |= WDOG_IRQ_EN;
    DEV_RMU->WDOG |= WDOG_EN;
}

void hal_Watchdog_clearITPendingBit(void)
{
    DEV_RMU->WDOG |= WDOG_PD;
}

uint32_t hal_watchdog_get_timeout(void)
{
    uint32_t timeout;
    timeout = DEV_RMU->WDOG & WDOG_TIME_MASK;

    switch (timeout)
    {
    case 0x00000000UL:
        timeout = 10;
        break;

    case 0x00000010UL:
        timeout = 125;
        break;

    case 0x00000020UL:
        timeout = 250;
        break;

    case 0x00000030UL:
        timeout = 500;
        break;

    case 0x00000040UL:
        timeout = 1000;
        break;

    case 0x00000050UL:
        timeout = 2000;
        break;

    case 0x00000060UL:
        timeout = 4000;
        break;

    case 0x00000070UL:
        timeout = 8000;
        break;
    }

    return timeout;
}

void hal_watchdog_set_timeout(uint32_t timeout)
{
    switch (timeout)
    {
    case 10:
        DEV_RMU->WDOG &= ~WDOG_TIME_MASK;
        DEV_RMU->WDOG |= 0x00000000UL;
        break;

    case 125:
        DEV_RMU->WDOG &= ~WDOG_TIME_MASK;
        DEV_RMU->WDOG |= 0x00000010UL;
        break;

    case 250:
        DEV_RMU->WDOG &= ~WDOG_TIME_MASK;
        DEV_RMU->WDOG |= 0x00000020UL;
        break;

    case 500:
        DEV_RMU->WDOG &= ~WDOG_TIME_MASK;
        DEV_RMU->WDOG |= 0x00000030UL;
        break;

    case 1000:
        DEV_RMU->WDOG &= ~WDOG_TIME_MASK;
        DEV_RMU->WDOG |= 0x00000040UL;
        break;

    case 2000:
        DEV_RMU->WDOG &= ~WDOG_TIME_MASK;
        DEV_RMU->WDOG |= 0x00000050UL;
        break;

    case 4000:
        DEV_RMU->WDOG &= ~WDOG_TIME_MASK;
        DEV_RMU->WDOG |= 0x00000060UL;
        break;

    case 8000:
        DEV_RMU->WDOG &= ~WDOG_TIME_MASK;
        DEV_RMU->WDOG |= 0x00000070UL;
        break;
    }
}
/**
 * detail: orange do not support get timeleft
 * @return 0
 */
uint32_t hal_watchdog_get_timeLeft(void)
{
    return 0;
}

void hal_watchdog_keep_alive(void)
{
    DEV_RMU->WDOG |= WDOG_CLR;
}

void hal_watchdog_start(void)
{
    DEV_RMU->WDOG |= WDOG_EN;
}

void hal_watchdog_stop(void)
{
    DEV_RMU->WDOG &= ~WDOG_EN;
}

__WEAK void wdog_irq_handler(void)
{
    hal_watchdog_keep_alive();
    hal_Watchdog_clearITPendingBit();
}
