#include <time.h>
#include <Xm/Form.h>
#include <Vk/VkApp.h>
#include "Clock.h"
#include "DynamicLabel.h"

XtResource Clock::_resources[] = 
{
  {
    // Format for strftime()
    "format",
    "Format",
    XmRString,
    sizeof(char *),
    XtOffset(Clock *, _timeFormat),
    XmRString,
    "%b %d %Y  %H:%M:%S UTC"
  }
};


Clock::Clock(const char *name, Widget parent)
{
  _face = 0;
  
  _baseWidget = 
    XtVaCreateWidget(name, xmFormWidgetClass, parent, NULL);
  
  installDestroyHandler();
  getResources(_resources, XtNumber(_resources));
  
  _face = new DynamicLabel("face", _baseWidget);
  _face->show();

  update();
  startTimer();
}


Clock::~Clock()
{
  delete _face;
}


void Clock::update()
{
  char buf[256];
  
  const time_t sec = time(NULL);
  struct tm *timePtr = gmtime(&sec);
  strftime(buf, sizeof(buf), _timeFormat, timePtr);

  _face->setText(buf);
}


void Clock::startTimer()
{
  _timer = 
    XtAppAddTimeOut(theApplication->appContext(), 1000,
		    &Clock::timerCallback, (XtPointer )this);  
}


void Clock::timerCallback(XtPointer clientData, XtIntervalId *id)
{
  Clock *obj = (Clock *)clientData;
  obj->update();
  obj->startTimer();
}

