/*
  This file is part of CDO. CDO is a collection of Operators to manipulate and analyse Climate model Data.

  Author: Uwe Schulzweida

*/

#include <cdi.h>

#include "datetime.h"
#include "calendar.h"
#include "timebase.h"

JulianDate
juldate_encode(int calendar, int64_t date, int time)
{
  int year, month, day, hour, minute, second;
  cdiDecodeDate(date, &year, &month, &day);
  cdiDecodeTime(time, &hour, &minute, &second);

  JulianDate juldate;
  encode_caldaysec(calendar, year, month, day, hour, minute, second, &juldate.julday, &juldate.secofday);

  return juldate;
}

void
juldate_decode(int calendar, const JulianDate &juldate, int64_t &date, int &time)
{
  int year, month, day, hour, minute, second;
  decode_caldaysec(calendar, juldate.julday, juldate.secofday, &year, &month, &day, &hour, &minute, &second);

  date = cdiEncodeDate(year, month, day);
  time = cdiEncodeTime(hour, minute, second);
}

JulianDate
juldate_sub(const JulianDate &juldate2, const JulianDate &juldate1)
{
  JulianDate juldate;

  (void) julday_sub(juldate1.julday, juldate1.secofday, juldate2.julday, juldate2.secofday, &juldate.julday, &juldate.secofday);

  return juldate;
}

JulianDate
juldate_add_seconds(int64_t seconds, const JulianDate &juldate)
{
  JulianDate juldate_new = juldate;

  julday_add_seconds(seconds, &juldate_new.julday, &juldate_new.secofday);

  return juldate_new;
}

double
juldate_to_seconds(const JulianDate &juldate)
{
  return juldate.julday * 86400. + juldate.secofday;
}
