#include <stdio.h>
#include <string.h>

#include "lephisto.h"
#include "hook.h"
#include "ltime.h"

static unsigned int lephisto_time = 0;

/* Get the current time. */
unsigned int ltime_get(void) {
  return lephisto_time;
}

/* Return the time in pretty text. */
char* ltime_pretty(unsigned int t) {
  unsigned int lt;
  int maj, stu;
  char str[128], *ret;

  if(t == 0) lt = lephisto_time;
  else lt = t;

  /* UST (Universal Synchronized Time) - unit is STU (Syncronized Time Unit). */
  maj = lt / (1000*LTIME_UNIT_LENGTH);
  stu = (lt / (LTIME_UNIT_LENGTH)) % 1000;
  if(maj == 0) /* Only STU. */
    snprintf(str, 128, "%03d STU", stu);
  else /* Full format. */
    snprintf(str, 128, "UST %d.%03d", maj, stu);
  ret = strdup(str);

  return ret;
}

/* Set the time absolutely, does *not* generate an event, used at init. */
void ltime_set(unsigned int t) {
  lephisto_time = t;
}

/* Set the time relatively. */
void ltime_inc(unsigned int t) {
  lephisto_time += t;

  hooks_run("time");
}