#include <time.h>
#include "toba.h"
#include "runtime.h"
#include "java_util_Date.h"

static time_t
get_time_t(struct in_java_util_Date *arg)
{
    struct tm t;

    if(arg->valueValid == JAVA_TRUE) {
        /* value = milliseconds */
        return arg->value / 1000;
    }

    /* we have to compute the value from the tm_ fields */
    t.tm_sec = arg->tm_sec;
    t.tm_min = arg->tm_min;
    t.tm_hour = arg->tm_hour;
    t.tm_mday = arg->tm_mday;
    t.tm_mon = arg->tm_mon;
    t.tm_wday = arg->tm_wday;
    t.tm_yday = arg->tm_yday;
    t.tm_year = arg->tm_year;
    t.tm_isdst = arg->tm_isdst;

    /* remember it for next time */
    arg->value = (Long)mktime(&t) * 1000;
    arg->valueValid = JAVA_TRUE;

    return arg->value;
}


/* java/util/Date toString ()Ljava/lang/String; */
Object toString__xcko0(Object Harg1) 
{
    struct in_java_util_Date *this = (struct in_java_util_Date *)Harg1;
    time_t t;
    char buf[50];

    t = get_time_t(this);
#ifdef __CYGWIN32__
    /* uses DOS strftime codes */
    strftime(buf, 50, "%a %b %d %H:%M:%S %z %Y", localtime(&t));
#else
    strftime(buf, 50, "%a %b %d %H:%M:%S %Z %Y", localtime(&t));
#endif

    return javastring(buf);
}

/* java/util/Date toLocaleString ()Ljava/lang/String; */
Object toLocaleString__zLzgu(Object Harg1) 
{
    struct in_java_util_Date *this = (struct in_java_util_Date *)Harg1;
    time_t t;
    char buf[50];

    t = get_time_t(this);
    strftime(buf, 50, "%c", localtime(&t));

    return javastring(buf);
}

/* java/util/Date toGMTString ()Ljava/lang/String; */
Object toGMTString__nLw3b(Object Harg1) 
{
    struct in_java_util_Date *this = (struct in_java_util_Date *)Harg1;
    time_t t;
    char buf[50];

    t = get_time_t(this);
    strftime(buf, 50, "%d %b %Y %H:%M:%S GMT", gmtime(&t));

    return javastring(buf);
}

/* java/util/Date expand ()V */
Void expand__D9q1g(Object Harg1) 
{
    struct in_java_util_Date *this = (struct in_java_util_Date *)Harg1;
    struct tm *tmp;
    time_t t;

    /* can only expand a valid value */
    if(this->valueValid == JAVA_FALSE)
        return;

    t = this->value / 1000;
    tmp = localtime(&t);
    this->tm_millis = 0;
    this->tm_sec = tmp->tm_sec;
    this->tm_min = tmp->tm_min;
    this->tm_hour = tmp->tm_hour;
    this->tm_mday = tmp->tm_mday;
    this->tm_mon = tmp->tm_mon;
    this->tm_year = tmp->tm_year;
    this->tm_wday = tmp->tm_wday;
    this->tm_yday = tmp->tm_yday;
    this->tm_isdst = tmp->tm_isdst;
    this->expanded = JAVA_TRUE;
}

/* java/util/Date computeValue ()V */
Void computeValue__Z112H(Object Harg1) 
{
    struct in_java_util_Date *this = (struct in_java_util_Date *)Harg1;

    /* get_time_t computes and sets the value as a side effect */
    (void)get_time_t(this);
}

