// $Id: afartime.c,v 1.4 2011/08/25 22:35:49 lpoulsen Exp $
//
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <string.h>
#ifndef LINUX
#include <windows.h>
#endif
#include <errno.h>
#include "afartype.h"
#include "epacket.h"
#include "afarutil.h"
#include "ucon.h"

time_t     afar_time_val;
struct tm *afar_tm_p;


char *
afar_date(const time_t t)
{
    static char afar_date_str[12];

    afar_time_val = (t ? t : time(0));
    afar_tm_p     = localtime(&afar_time_val);

    sprintf(afar_date_str, "%4d-%02d-%02d",
            afar_tm_p->tm_year+1900, afar_tm_p->tm_mon+1, afar_tm_p->tm_mday);
    return afar_date_str;
}

char *
afar_time(const time_t t)
{
    static char afar_time_str[12];

    if (debug_flags & DBFLG_DATE_TIME) printf("afar_time(%d)\n", (int)t);

    afar_time_val = (t ? t : time(0));
    afar_tm_p     = localtime(&afar_time_val);
    if (afar_tm_p == NULL) {
        printf("afar_time() failed localtime()\n");
        printf("   sizeof(time_t) = %d %d\n",
               sizeof(time_t), sizeof(afar_time_val));
        printf("   failed to convert %d (0x%08X)\n",
               (int)afar_time_val, (unsigned int)afar_time_val);
        printf("   time(0) = %d (0x%08X)\n",
               (int)time(0), (unsigned int)time(0));
        exit(-1);
    }
    if (debug_flags & DBFLG_DATE_TIME)
        printf("afar_time(%d) localtime() done\n", (int)t);

    sprintf(afar_time_str, "%02d:%02d:%02d",
            afar_tm_p->tm_hour, afar_tm_p->tm_min, afar_tm_p->tm_sec);
    if (debug_flags & DBFLG_DATE_TIME) printf("afar_time() = %s\n", afar_time_str);
    return afar_time_str;
}
#ifndef LINUX
char *
afar_date_64(const time64_t t)
{
    static char afar_date_str[12];
    SYSTEMTIME  afar_syst;

    if (t) {
        FileTimeToSystemTime((void *)&t, &afar_syst);
    } else {
        GetLocalTime(&afar_syst);
    }

    sprintf(afar_date_str, "%4d-%02d-%02d",
            afar_syst.wYear, afar_syst.wMonth, afar_syst.wDay);
    return afar_date_str;
}

char *
afar_time_64(const time64_t t)
{
    static char afar_time_str[12];
    SYSTEMTIME  afar_syst;

    if (t) {
        FileTimeToSystemTime((void *)&t, &afar_syst);
    } else {
        GetLocalTime(&afar_syst);
    }

    sprintf(afar_time_str, "%02d:%02d:%02d",
            afar_syst.wHour, afar_syst.wMinute, afar_syst.wSecond);
    return afar_time_str;
}
#endif
