#include "ptimer.h"

static void com_ptimer_notify_function(union sigval v)
{
    ptimer_t *ptimer = (ptimer_t *)v.sival_ptr;
    ptimer->timeout_callback(ptimer->priv);
}

void com_ptimer_init(ptimer_t *ptimer, const char* type, void (*timeout_callback)(void* priv), void *priv)
{
    if (ptimer)
    {
        ptimer->priv = priv;
        ptimer->timeout_callback = timeout_callback;

        memset(&ptimer->evp, 0, sizeof(ptimer->evp));
        // ptimer->evp.sigev_value.sival_int = 3;
        ptimer->evp.sigev_value.sival_ptr = ptimer;

        ptimer->evp.sigev_notify = SIGEV_THREAD;
        ptimer->evp.sigev_notify_function = com_ptimer_notify_function;

        if (strcmp(type, "systime")==0)
        {
            if (timer_create(CLOCK_REALTIME, &ptimer->evp, &ptimer->timerid)!=0)
            {
                printe(":%p\n",ptimer);
            }
        }else{
            if (timer_create(CLOCK_MONOTONIC, &ptimer->evp, &ptimer->timerid)!=0)
            {
                printe(":%p\n",ptimer);
            }
        }
    }
}

void com_ptimer_reset(ptimer_t *ptimer, int start_ms, int interval_ms)
{
    if (ptimer)
    {
        ptimer->it.it_interval.tv_sec  = interval_ms/1000;
        ptimer->it.it_interval.tv_nsec = (interval_ms%1000) * 1000;

        ptimer->it.it_value.tv_sec  = start_ms/1000;
        ptimer->it.it_value.tv_nsec = (start_ms%1000) * 1000;

        if (timer_settime(ptimer->timerid, TIMER_ABSTIME, &ptimer->it, NULL)!=0)
        {
            printe(":%p\n",ptimer);
        }
    }
}

void com_ptimer_exit(ptimer_t *ptimer)
{
    if (ptimer)
    {
        if (timer_delete(ptimer->timerid)!=0)
        {
            printe(":%p\n",ptimer);
        }
    }
}