/* Copyright (c) 2025, Canaan Bright Sight Co., Ltd
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 1. Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <cstddef>
#include <cstdint>
#include <cstdio>

#include "api/HardwareTimer.h"

namespace arduino {

HardwareTimer::HardwareTimer(uint8_t timer_num)
  : timer_id(timer_num), timer_inst(NULL), is_initialized(false), is_started(false),
    auto_reload(true), frequency(12500000), period_ms(1000)
#if !CONFIG_DISABLE_HAL_LOCKS
    , lock(NULL)
#endif
{
}

HardwareTimer::~HardwareTimer() {
    end();
#if !CONFIG_DISABLE_HAL_LOCKS
    if (NULL != lock) {
        pthread_mutex_destroy(lock);
    }
#endif
}

void HardwareTimer::timerISRHandler(void* args) {
    HardwareTimer* timer = (HardwareTimer*)args;
    if (timer == NULL) {
        return;
    }

    if (timer->user_callback) {
        timer->user_callback();
    } else if (timer->user_callback_arg) {
        timer->user_callback_arg(timer->user_arg);
    }
}

bool HardwareTimer::begin(uint32_t freq_hz) {
    if (timer_id >= KD_TIMER_MAX_NUM) {
        printf("%s: Invalid timer id %d\n", __func__, timer_id);
        return false;
    }

    if (freq_hz < 12500000 || freq_hz > 100000000) {
        printf("%s: Invalid freq_hz %d, freq range in [12500000 ~ 100000000]\n", __func__);
        return false;
    }

#if !CONFIG_DISABLE_HAL_LOCKS
    if (lock == NULL) {
        lock = &_lock;
        if (0 != pthread_mutex_init(lock, NULL)) {
            printf("%s: pthread_mutex_init failed\n", __func__);
            return false;
        }
    }
    //acquire lock
    if (0 != pthread_mutex_lock(lock)) {
        printf("%s: could not acquire lock\n", __func__);
        return false;
    }
#endif

    bool ret = false;
    int err = 0;

    if (is_initialized) {
        printf("%s: Timer%d already initialized\n", __func__, timer_id);
        ret = true;
    } else {
        err = drv_hard_timer_inst_create(timer_id, &timer_inst);
        if (err != 0) {
            printf("%s: drv_hard_timer_inst_create failed: %d\n", __func__, err);
        } else {
            // Set default frequency
            frequency = freq_hz;
            err = drv_hard_timer_set_freq(timer_inst, frequency);
            if (err != 0) {
                printf("%s: drv_hard_timer_set_freq failed: %d\n", __func__, err);
                drv_hard_timer_inst_destroy(&timer_inst);
            } else {
                // Set default mode to periodic
                err = drv_hard_timer_set_mode(timer_inst, auto_reload ? HWTIMER_MODE_PERIOD : HWTIMER_MODE_ONESHOT);
                if (err != 0) {
                    printf("%s: drv_hard_timer_set_mode failed: %d\n", __func__, err);
                    drv_hard_timer_inst_destroy(&timer_inst);
                } else {
                    is_initialized = true;
                    ret = true;
                }
            }
        }
    }

#if !CONFIG_DISABLE_HAL_LOCKS
    //release lock
    pthread_mutex_unlock(lock);
#endif
    return ret;
}

bool HardwareTimer::end() {
#if !CONFIG_DISABLE_HAL_LOCKS
    if (lock != NULL) {
        //acquire lock
        if (0 != pthread_mutex_lock(lock)) {
            printf("%s: could not acquire lock\n", __func__);
            return false;
        }
    }
#endif

    if (is_started) {
        stop();
    }

    if (timer_inst != NULL) {
        drv_hard_timer_inst_destroy(&timer_inst);
        timer_inst = NULL;
    }

    is_initialized = false;
    is_started = false;

#if !CONFIG_DISABLE_HAL_LOCKS
    if (lock != NULL) {
        //release lock
        pthread_mutex_unlock(lock);
    }
#endif
    return true;
}

bool HardwareTimer::start() {
    if (!is_initialized || timer_inst == NULL) {
        printf("%s: Timer not initialized\n", __func__);
        return false;
    }

#if !CONFIG_DISABLE_HAL_LOCKS
    //acquire lock
    if (lock == NULL || 0 != pthread_mutex_lock(lock)) {
        printf("%s: could not acquire lock\n", __func__);
        return false;
    }
#endif

    int err = drv_hard_timer_start(timer_inst);
    if (err != 0) {
        printf("%s: drv_hard_timer_start failed: %d\n", __func__, err);
    } else {
        is_started = true;
    }

#if !CONFIG_DISABLE_HAL_LOCKS
    //release lock
    pthread_mutex_unlock(lock);
#endif

    return (err == 0);
}

bool HardwareTimer::stop() {
    if (!is_initialized || timer_inst == NULL) {
        return false;
    }

#if !CONFIG_DISABLE_HAL_LOCKS
    //acquire lock
    if (lock == NULL || 0 != pthread_mutex_lock(lock)) {
        printf("%s: could not acquire lock\n", __func__);
        return false;
    }
#endif

    int err = drv_hard_timer_stop(timer_inst);
    if (err != 0) {
        printf("%s: drv_hard_timer_stop failed: %d\n", __func__, err);
    } else {
        is_started = false;
    }

#if !CONFIG_DISABLE_HAL_LOCKS
    //release lock
    pthread_mutex_unlock(lock);
#endif

    return (err == 0);
}

bool HardwareTimer::restart() {
    if (!stop()) {
        return false;
    }
    return start();
}

bool HardwareTimer::setMode(bool auto_reload_mode) {
    if (!is_initialized || timer_inst == NULL) {
        printf("%s: Timer not initialized\n", __func__);
        return false;
    }

    if (is_started) {
        printf("%s: Cannot change mode while timer is running\n", __func__);
        return false;
    }

#if !CONFIG_DISABLE_HAL_LOCKS
    //acquire lock
    if (lock == NULL || 0 != pthread_mutex_lock(lock)) {
        printf("%s: could not acquire lock\n", __func__);
        return false;
    }
#endif

    auto_reload = auto_reload_mode;
    rt_hwtimer_mode_t mode = auto_reload ? HWTIMER_MODE_PERIOD : HWTIMER_MODE_ONESHOT;
    int err = drv_hard_timer_set_mode(timer_inst, mode);
    if (err != 0) {
        printf("%s: drv_hard_timer_set_mode failed: %d\n", __func__, err);
    }

#if !CONFIG_DISABLE_HAL_LOCKS
    //release lock
    pthread_mutex_unlock(lock);
#endif

    return (err == 0);
}

bool HardwareTimer::setFrequency(uint32_t freq_hz) {
    if (!is_initialized || timer_inst == NULL) {
        printf("%s: Timer not initialized\n", __func__);
        return false;
    }

    if (is_started) {
        printf("%s: Cannot change frequency while timer is running\n", __func__);
        return false;
    }

    if (freq_hz < 12500000 || freq_hz > 100000000) {
        printf("%s: Invalid freq_hz %d, freq range in [12500000 ~ 100000000]\n", __func__);
        return false;
    }

#if !CONFIG_DISABLE_HAL_LOCKS
    //acquire lock
    if (lock == NULL || 0 != pthread_mutex_lock(lock)) {
        printf("%s: could not acquire lock\n", __func__);
        return false;
    }
#endif

    frequency = freq_hz;
    int err = drv_hard_timer_set_freq(timer_inst, frequency);
    if (err != 0) {
        printf("%s: drv_hard_timer_set_freq failed: %d\n", __func__, err);
    }

#if !CONFIG_DISABLE_HAL_LOCKS
    //release lock
    pthread_mutex_unlock(lock);
#endif

    return (err == 0);
}

bool HardwareTimer::setPeriod(uint32_t period_ms_val) {
    if (!is_initialized || timer_inst == NULL) {
        printf("%s: Timer not initialized\n", __func__);
        return false;
    }

    if (is_started) {
        printf("%s: Cannot change period while timer is running\n", __func__);
        return false;
    }

#if !CONFIG_DISABLE_HAL_LOCKS
    //acquire lock
    if (lock == NULL || 0 != pthread_mutex_lock(lock)) {
        printf("%s: could not acquire lock\n", __func__);
        return false;
    }
#endif

    int err = drv_hard_timer_set_period(timer_inst, period_ms_val);
    if (err != 0) {
        printf("%s: drv_hard_timer_set_period failed: %d\n", __func__, err);
    } else {
        period_ms = period_ms_val;
    }

#if !CONFIG_DISABLE_HAL_LOCKS
    //release lock
    pthread_mutex_unlock(lock);
#endif

    return (err == 0);
}

bool HardwareTimer::setAlarm(uint32_t alarm_ms) {
    return setPeriod(alarm_ms);
}

uint32_t HardwareTimer::getFrequency() {
    if (!is_initialized || timer_inst == NULL) {
        return 0;
    }

#if !CONFIG_DISABLE_HAL_LOCKS
    //acquire lock
    if (lock == NULL || 0 != pthread_mutex_lock(lock)) {
        printf("%s: could not acquire lock\n", __func__);
        return 0;
    }
#endif

    uint32_t freq = 0;
    int err = drv_hard_timer_get_freq(timer_inst, &freq);
    if (err != 0) {
        printf("%s: drv_hard_timer_get_freq failed: %d\n", __func__, err);
    }

#if !CONFIG_DISABLE_HAL_LOCKS
    //release lock
    pthread_mutex_unlock(lock);
#endif

    return freq;
}

uint32_t HardwareTimer::getPeriod() {
    return period_ms;
}

void HardwareTimer::attachInterrupt(const std::function<void()>& callback) {
    if (!is_initialized || timer_inst == NULL) {
        printf("%s: Timer not initialized\n", __func__);
        return;
    }

    if (is_started) {
        printf("%s: Cannot attach interrupt while timer is running\n", __func__);
        return;
    }

#if !CONFIG_DISABLE_HAL_LOCKS
    //acquire lock
    if (lock == NULL || 0 != pthread_mutex_lock(lock)) {
        printf("%s: could not acquire lock\n", __func__);
        return;
    }
#endif

    user_callback = callback;
    user_callback_arg = nullptr;
    user_arg = nullptr;

    int err = drv_hard_timer_register_irq(timer_inst, timerISRHandler, this);
    if (err != 0) {
        printf("%s: drv_hard_timer_register_irq failed: %d\n", __func__, err);
    }

#if !CONFIG_DISABLE_HAL_LOCKS
    //release lock
    pthread_mutex_unlock(lock);
#endif
}

void HardwareTimer::attachInterruptArg(const std::function<void(void*)>& callback, void* arg) {
    if (!is_initialized || timer_inst == NULL) {
        printf("%s: Timer not initialized\n", __func__);
        return;
    }

    if (is_started) {
        printf("%s: Cannot attach interrupt while timer is running\n", __func__);
        return;
    }

#if !CONFIG_DISABLE_HAL_LOCKS
    //acquire lock
    if (lock == NULL || 0 != pthread_mutex_lock(lock)) {
        printf("%s: could not acquire lock\n", __func__);
        return;
    }
#endif

    user_callback = nullptr;
    user_callback_arg = callback;
    user_arg = arg;

    int err = drv_hard_timer_register_irq(timer_inst, timerISRHandler, this);
    if (err != 0) {
        printf("%s: drv_hard_timer_register_irq failed: %d\n", __func__, err);
    }

#if !CONFIG_DISABLE_HAL_LOCKS
    //release lock
    pthread_mutex_unlock(lock);
#endif
}

void HardwareTimer::detachInterrupt() {
    if (!is_initialized || timer_inst == NULL) {
        printf("%s: Timer not initialized\n", __func__);
        return;
    }

    if (is_started) {
        printf("%s: Cannot detach interrupt while timer is running\n", __func__);
        return;
    }

#if !CONFIG_DISABLE_HAL_LOCKS
    //acquire lock
    if (lock == NULL || 0 != pthread_mutex_lock(lock)) {
        printf("%s: could not acquire lock\n", __func__);
        return;
    }
#endif

    int err = drv_hard_timer_unregister_irq(timer_inst);
    if (err != 0) {
        printf("%s: drv_hard_timer_unregister_irq failed: %d\n", __func__, err);
    }

    user_callback = nullptr;
    user_callback_arg = nullptr;
    user_arg = nullptr;

#if !CONFIG_DISABLE_HAL_LOCKS
    //release lock
    pthread_mutex_unlock(lock);
#endif
}

// Global timer instances
HardwareTimer Timer0(0);
HardwareTimer Timer1(1);
HardwareTimer Timer2(2);
HardwareTimer Timer3(3);
HardwareTimer Timer4(4);
HardwareTimer Timer5(5);

} // namespace arduino
