#pragma once

#ifndef TIMESPEC_H_F2918131_13EC_4f01_A797_55061EE3EE64
#define TIMESPEC_H_F2918131_13EC_4f01_A797_55061EE3EE64

#include <time.h>

inline bool operator<(const timespec &rhs1, const timespec &rhs2) {
    if (rhs1.tv_sec < rhs2.tv_sec) {
        return true;
    }
    if (rhs1.tv_sec > rhs2.tv_sec) {
        return false;
    }
    if (rhs1.tv_nsec < rhs2.tv_nsec) {
        return true;
    }
    return false;
}

inline bool operator==(const timespec &rhs1, const timespec &rhs2) {
    if ((rhs1.tv_sec == rhs2.tv_sec) && (rhs1.tv_nsec == rhs2.tv_nsec)) {
        return true;
    }
    return false;
}

inline timespec operator-(timespec rhs1, const timespec &rhs2) {
    if (rhs1.tv_nsec >= rhs2.tv_nsec) {
        rhs1.tv_nsec -= rhs2.tv_nsec;
    } else {
        rhs1.tv_nsec += 1000000000;
        rhs1.tv_nsec -= rhs2.tv_nsec;
        rhs1.tv_sec -= 1;
    }

    rhs1.tv_sec -= rhs2.tv_sec;
    return rhs1;
}

inline timespec operator+(timespec rhs1, const timespec &rhs2) {
    rhs1.tv_sec += rhs2.tv_sec;
    rhs1.tv_nsec += rhs2.tv_nsec;
    if (rhs1.tv_nsec >= 1000000000) {
        rhs1.tv_nsec -= 1000000000;
        rhs1.tv_sec += 1;
    }
    return rhs1;
}

inline timespec get_alarm_timer_from_ms(unsigned long time_ms) {
    timespec timer;
    timer.tv_sec = time_ms / 1000;
    time_ms %= 1000;
    timer.tv_nsec = time_ms * 1000000;
    return timer;
}

#endif //TIMESPEC_H_F2918131_13EC_4f01_A797_55061EE3EE64
