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

  Copyright (C) 2003-2020 Uwe Schulzweida, <uwe.schulzweida AT mpimet.mpg.de>
  See COPYING file for copying and redistribution conditions.

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; version 2 of the License.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
*/
#include <cdi.h>

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

JulianDate
julianDateEncode(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
julianDateDecode(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
julianDateSub(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
julianDateAddSeconds(int64_t seconds, const JulianDate &juldate)
{
  JulianDate juldate_new = juldate;

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

  return juldate_new;
}

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