/*
  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.
*/

/*
   This module contains the following operators:

      Arithdays  muldpm          Multiply with days per month
      Arithdays  divdpm          Divide by days per month
      Arithdays  muldpy          Multiply with days per year
      Arithdays  divdpy          Divide by days per year
      Arithdays  muldoy          Multiply with day of year
*/

#include <cdi.h>

#include "cdo_options.h"
#include "functs.h"
#include "process_int.h"
#include "calendar.h"

static double
dayofyear(int calendar, int64_t vdate, int vtime)
{
  const int month_360[12] = { 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30 };
  const int month_365[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  const int month_366[12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

  int year, month, day;
  int hour, minute, second;
  cdiDecodeDate(vdate, &year, &month, &day);
  cdiDecodeTime(vtime, &hour, &minute, &second);

  const auto dpy = days_per_year(calendar, year);

  double doy = 0;
  for (int im = 1; im < month; ++im)
    {
      auto dpm = (dpy == 360) ? month_360 : ((dpy == 365) ? month_365 : month_366);
      if (im >= 1 && im <= 12) doy += dpm[im - 1];
    }

  doy += (day - 1);
  doy += (second + minute * 60 + hour * 3600) / 86400.;

  if (Options::cdoVerbose) cdoPrint("vdate, vtime, dpy, doy: %d %d %d %g", vdate, vtime, dpy, doy);

  return doy;
}

void *
Arithdays(void *process)
{
  int nrecs;
  int varID, levelID;
  int year, month, day;

  cdoInitialize(process);

  // clang-format off
               cdoOperatorAdd("muldpm", func_mul, func_month, nullptr);
               cdoOperatorAdd("divdpm", func_div, func_month, nullptr);
               cdoOperatorAdd("muldpy", func_mul, func_year,  nullptr);
               cdoOperatorAdd("divdpy", func_div, func_year,  nullptr);
  int MULDOY = cdoOperatorAdd("muldoy", func_mul,         0,  nullptr);
  // clang-format on

  const auto operatorID = cdoOperatorID();
  const auto operfunc = cdoOperatorF1(operatorID);
  const auto operfunc2 = cdoOperatorF2(operatorID);

  operatorCheckArgc(0);

  const auto streamID1 = cdoOpenRead(0);

  const auto vlistID1 = cdoStreamInqVlist(streamID1);
  const auto vlistID2 = vlistDuplicate(vlistID1);

  const auto taxisID1 = vlistInqTaxis(vlistID1);
  const auto taxisID2 = taxisDuplicate(taxisID1);
  vlistDefTaxis(vlistID2, taxisID2);

  const auto calendar = taxisInqCalendar(taxisID1);

  const auto streamID2 = cdoOpenWrite(1);
  cdoDefVlist(streamID2, vlistID2);

  const auto gridsizemax = vlistGridsizeMax(vlistID1);

  Field field;
  field.resize(gridsizemax);

  int tsID = 0;
  while ((nrecs = cdoStreamInqTimestep(streamID1, tsID)))
    {
      const auto vdate = taxisInqVdate(taxisID1);
      const auto vtime = taxisInqVtime(taxisID1);

      taxisCopyTimestep(taxisID2, taxisID1);
      cdoDefTimestep(streamID2, tsID);

      cdiDecodeDate(vdate, &year, &month, &day);

      double rconst;
      if (operatorID == MULDOY)
        rconst = dayofyear(calendar, vdate, vtime);
      else
        rconst = (operfunc2 == func_month) ? days_per_month(calendar, year, month) : days_per_year(calendar, year);

      if (Options::cdoVerbose) cdoPrint("calendar %d  year %d  month %d  result %g", calendar, year, month, rconst);

      for (int recID = 0; recID < nrecs; recID++)
        {
          cdoInqRecord(streamID1, &varID, &levelID);
          cdoReadRecord(streamID1, field.vec_d.data(), &field.nmiss);

          field.grid = vlistInqVarGrid(vlistID1, varID);
          field.missval = vlistInqVarMissval(vlistID1, varID);

          vfarcfun(field, rconst, operfunc);

          cdoDefRecord(streamID2, varID, levelID);
          cdoWriteRecord(streamID2, field.vec_d.data(), field.nmiss);
        }

      tsID++;
    }

  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  cdoFinish();

  return nullptr;
}
