/*
 * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
 *
 * This software is dual-licensed to you under the MIT License (MIT) and
 * the Universal Permissive License (UPL). See the LICENSE file in the root
 * directory for license terms. You may choose either license, or both.
 */

#include "iotcs_port_mqtt.h"
#include "us_ticker_api.h"

char expired(Timer* timer) {
    uint32_t now = us_ticker_read();
    int is_expired = (int32_t)(*((uint32_t*)timer) - now) < 0;
    /*if (is_expired) {
        LOG_DBG("Timer %p expired: %d - exp, %d - now", timer, *((uint32_t*)timer), now);
    } else {
        LOG_DBG("Timer %p not expired: %d - exp, %d - now", timer, *((uint32_t*)timer), now);
    }*/
    return (char)is_expired;
}

void countdown_ms(Timer* timer, unsigned int timeout) {
    /* LOG_DBG("Timer %p init to %d ms", timer, timeout); */
    *((uint32_t*)timer) = us_ticker_read() + (uint32_t)(timeout * 1000); /* to us */
}

void countdown(Timer* timer, unsigned int timeout) {
    /* LOG_DBG("Timer %p init to %d sec", timer, timeout); */
    *((uint32_t*)timer) = us_ticker_read() + (uint32_t)(timeout * 1000000); /* to us */
}

int left_ms(Timer* timer) {
    int32_t remain = (*((uint32_t*)timer) - us_ticker_read()) / 1000;
    /* LOG_DBG("Timer %p left %d ms", timer, remain > 0 ? remain : 0); */
    return remain > 0 ? remain : 0;
}

void InitTimer(Timer* timer) {
    (void)timer; /* no action required */
}
