#include "timer.h"

#include <unistd.h>

#include <thread>

Timer::Timer(int msec, bool single, void *parent)
    : m_interval(msec)
    , m_single(single)
    , m_parent(parent)
{
}

Timer::~Timer()
{
    stop();
    if (m_active) {
        pthread_join(m_threadId, nullptr);
    }
}

static void *callbackFunction(void *arg)
{
    Timer *timer = (Timer *)arg;
    timer->run();
    return nullptr;
}

bool Timer::start(std::function<void (void *)> function, unsigned int count)
{
    if (m_active)
        return false;

    m_count = count;

    m_stop = false;
    auto status = pthread_create(&m_threadId, NULL, callbackFunction, this);
    if (status != -1) {
        m_active = true;
        m_function = function;
    }
    return status != -1;
}

void Timer::setCount(unsigned int count)
{
    m_count = count;
}

void Timer::stop()
{
    m_stop = true;
}

bool Timer::isStop()
{
    return m_stop;
}

bool Timer::isActive()
{
    return m_active;
}

void Timer::run()
{
    while (!m_stop) {
        unsigned int curCount = m_count;
        for (size_t i = 0; i < curCount; i++) {
            if (m_interval > 0) {
                usleep(m_interval * 1000);
            }
            if (m_stop || curCount != m_count)
                break;
        }
        if (m_function && !m_stop && curCount == m_count) {
            m_function(m_parent);
        }
        if (m_single || nullptr == m_parent || nullptr == m_function)
            break;
    }
    m_active = false;
}
