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

      Yearmonstat   yearmonmean        Yearly mean from monthly data
      Yearmonstat   yearmonavg         Yearly average from monthly data
*/

#include <cdi.h>

#include "cdo_options.h"
#include "cdo_vlist.h"
#include "functs.h"
#include "process_int.h"
#include "calendar.h"
#include "datetime.h"
#include "printinfo.h"

void *
Yearmonstat(void *process)
{
  TimeStat timestat_date = TimeStat::MEAN;
  int64_t vdate0 = 0;
  int vtime0 = 0;
  int nrecs;
  int year0 = 0, month0 = 0;
  int year, month, day;

  cdoInitialize(process);

  // clang-format off
  cdoOperatorAdd("yearmonmean",  func_mean, 0, nullptr);
  cdoOperatorAdd("yearmonavg",   func_avg,  0, nullptr);
  // clang-format on

  const auto operatorID = cdoOperatorID();
  const auto operfunc = cdoOperatorF1(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);
  taxisWithBounds(taxisID2);
  vlistDefTaxis(vlistID2, taxisID2);

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

  const auto nvars = vlistNvars(vlistID1);

  const auto maxrecs = vlistNrecs(vlistID1);
  std::vector<RecordInfo> recList(maxrecs);

  const auto calendar = taxisInqCalendar(taxisID1);
  DateTimeList dtlist;
  dtlist.setStat(timestat_date);
  dtlist.setCalendar(calendar);

  VarList varList1;
  varListInit(varList1, vlistID1);

  const auto gridsizemax = vlistGridsizeMax(vlistID1);

  Field field;
  field.resize(gridsizemax);

  FieldVector2D samp1, vars1;
  fieldsFromVlist(vlistID1, samp1);
  fieldsFromVlist(vlistID1, vars1, FIELD_VEC);

  int tsID = 0;
  int otsID = 0;
  while (true)
    {
      long nsets = 0;
      double dsets = 0;
      while ((nrecs = cdoStreamInqTimestep(streamID1, tsID)))
        {
          dtlist.taxisInqTimestep(taxisID1, nsets);
          const auto vdate = dtlist.getVdate(nsets);
          const auto vtime = dtlist.getVtime(nsets);
          cdiDecodeDate(vdate, &year, &month, &day);

          if (nsets == 0) year0 = year;

          if (year != year0) break;

          if (nsets > 0 && month == month0)
            {
              cdoWarning("   last timestep: %s %s", dateToString(vdate0).c_str(), timeToString(vtime0).c_str());
              cdoWarning("current timestep: %s %s", dateToString(vdate).c_str(), timeToString(vtime).c_str());
              cdoAbort("Month does not change!");
            }

          const int dpm = days_per_month(calendar, year, month);

          for (int recID = 0; recID < nrecs; recID++)
            {
              int varID, levelID;
              cdoInqRecord(streamID1, &varID, &levelID);

              if (tsID == 0)
                {
                  recList[recID].varID = varID;
                  recList[recID].levelID = levelID;
                  recList[recID].lconst = varList1[varID].timetype == TIME_CONSTANT;
                }

              auto &rsamp1 = samp1[varID][levelID];
              auto &rvars1 = vars1[varID][levelID];

              const auto fieldsize = rvars1.size;

              if (nsets == 0)
                {
                  cdoReadRecord(streamID1, rvars1.vec_d.data(), &rvars1.nmiss);

                  vfarcmul(rvars1, dpm);

                  if (rvars1.nmiss || !rsamp1.empty())
                    {
                      if (rsamp1.empty()) rsamp1.resize(fieldsize);

                      for (size_t i = 0; i < fieldsize; i++)
                        rsamp1.vec_d[i] = (DBL_IS_EQUAL(rvars1.vec_d[i], rvars1.missval)) ? 0 : dpm;
                    }
                }
              else
                {
                  cdoReadRecord(streamID1, field.vec_d.data(), &field.nmiss);
                  field.size = fieldsize;
                  field.grid = rvars1.grid;
                  field.missval = rvars1.missval;

                  vfarcmul(field, dpm);

                  if (field.nmiss || !rsamp1.empty())
                    {
                      if (rsamp1.empty()) rsamp1.resize(fieldsize, dsets);

                      for (size_t i = 0; i < fieldsize; i++)
                        if (!DBL_IS_EQUAL(field.vec_d[i], rvars1.missval)) rsamp1.vec_d[i] += dpm;
                    }

                  vfarfun(rvars1, field, operfunc);
                }
            }

          month0 = month;
          vdate0 = vdate;
          vtime0 = vtime;
          nsets++;
          dsets += dpm;
          tsID++;
        }

      if (nrecs == 0 && nsets == 0) break;

      for (int varID = 0; varID < nvars; varID++)
        {
          if (varList1[varID].timetype == TIME_CONSTANT) continue;
          const auto nlevels = varList1[varID].nlevels;
          for (int levelID = 0; levelID < nlevels; levelID++)
            {
              if (samp1[varID][levelID].empty())
                vfarcdiv(vars1[varID][levelID], dsets);
              else
                vfardiv(vars1[varID][levelID], samp1[varID][levelID]);
            }
        }

      if (Options::cdoVerbose)
        {
          cdoPrint("%s %s  nsets = %ld", dateToString(vdate0).c_str(), timeToString(vtime0).c_str(), nsets);
        }

      dtlist.statTaxisDefTimestep(taxisID2, nsets);
      cdoDefTimestep(streamID2, otsID);

      for (int recID = 0; recID < maxrecs; recID++)
        {
          if (otsID && recList[recID].lconst) continue;

          const auto varID = recList[recID].varID;
          const auto levelID = recList[recID].levelID;
          auto &rvars1 = vars1[varID][levelID];
          cdoDefRecord(streamID2, varID, levelID);
          cdoWriteRecord(streamID2, rvars1.vec_d.data(), rvars1.nmiss);
        }

      if (nrecs == 0) break;
      otsID++;
    }

  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  cdoFinish();

  return nullptr;
}
