/// @file RTClock.h
/// @brief communicate with RTC chip

#ifndef RTCLOCK_H
#define	RTCLOCK_H
#include "cwgsys.h"
#include "pic24.h"
#include <time.h>

/// @typedef struct tm Time
/// @brief rename struct tm for convenience
typedef struct tm Time;

/// @def TM2ISO8601(ptm, dest)
/// @brief format Time as ISO8601 format string in dest
/// @param ptm pointer to Time 
/// @param dest destination (min 21 bytes)
/// @return length of dest on success, -1 otherwise
#define TM2ISO8601(ptm, dest) sprintf(dest,"%04u-%02u-%02uT%02u:%02u:%02uZ",1900+ptm->tm_year, ptm->tm_mon+1, ptm->tm_mday,ptm->tm_hour, ptm->tm_min, ptm->tm_sec)
/// @def TM2POSIX(ptm, dest)
/// @brief format Time struct as posix epoch seconds
/// @param ptm pointer to Time 
/// @param dest destination (min 21 bytes)
/// @return length of dest on success, -1 otherwise
#define TM2POSIX(ptm, dest) sprintf(dest,"%ld",rtc_mktime(ptm))
/// @def TM2POSIXMS(ptm, dest)
/// @brief format Time struct as posix epoch milliseconds
/// @param ptm pointer to Time 
/// @param dest destination (min 21 bytes)
/// @return length of dest on success, -1 otherwise
#define TM2POSIXMS(ptm, dest) sprintf(dest,"%lld",(rtc_mktime(ptm)*1000))
/// @def LL2POSIXMS(ll, dest)
/// @brief format long long int to posix epoch milliseconds
/// @param ll  epoch time (long long int)
/// @param dest destination (min 21 bytes)
/// @return length of dest on success, -1 otherwise
#define LL2POSIXMS(ll, dest) sprintf(dest,"%lld",ll)
/// @def LL2POSIXDS(ll, dest)
/// @brief format long long int to posix epoch decimal seconds (3 decimal places)
/// @param ll  epoch time (long long int)
/// @param dest destination (min 21 bytes)
/// @return length of dest on success, -1 otherwise
#define LL2POSIXDS(ll, dest) sprintf(dest,"%.3lf",(ll/1000.0))

//#define DTM2POSIX(dtm, dest) sprintf(dest,"%lld",dtm)

/// @brief get current time
/// @param [out] now Time struct to fill 
void rtcRead(Time* now);
/// @brief set RTC's time
/// @param now Time to set to
void rtcSetTime(const Time* now);
/// @brief set the alarm timer on RTC
/// @param alarm Time fro alarm
void rtcSetAlarm(const Time *alarm);
/// @brief check if the RTC alarm went off
/// @return TRUE if alarm past
int rtcDidAlarm();
/// @brief make a string in YYYY/MM/DD hh:mm:ss format out of a Time
/// @param [out] buff buffer for string
/// @param now Time to be printed
/// @return pointer to end of string
char* rtcPrint(char* buff, const Time* now);
/// @brief make a string in YYYY/MM/DD hh:mm:ss format of current time
/// @param [out] buff buffer for string
/// @return pointer to end of string
char* rtcPrintNow(char* buff);
/// @brief reset/init RTC settings
void rtcReset();
/// @brief get current time as unix time
/// @return time_t(seconds from 1970.1.1)
time_t rtc_mktime(Time *tm_out);
/// @brief timestamp for file system, not much use otherwise
/// @return 32bit-field, custom time format
DWORD get_fattime();
void EX_INT0_CallBack(void);

#endif	/// RTCLOCK_H 