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

  Copyright (C) 2006 Brockmann Consult
  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:

      Timcount    timcount          Time counts
      Hourcount   hourcount         Hourly counts
      Daycount    daycount          Daily counts
      Moncount    moncount          Monthly counts
      Yearcount   yearcount         Yearly counts
*/

#include <cdi.h>

#include "process_int.h"
#include "util_date.h"

void *
Timcount(void *process)
{
  char indate1[DATE_LEN + 1], indate2[DATE_LEN + 1];
  int64_t vdate0 = 0;
  int vtime0 = 0;

  cdo_initialize(process);

  // clang-format off
  cdo_operator_add("timcount",  0, 31, nullptr);
  cdo_operator_add("yearcount", 0, 10, nullptr);
  cdo_operator_add("moncount",  0,  8, nullptr);
  cdo_operator_add("daycount",  0,  6, nullptr);
  cdo_operator_add("hourcount", 0,  4, nullptr);
  // clang-format on

  const auto operatorID = cdo_operator_id();

  const int cmplen = DATE_LEN - cdo_operator_f2(operatorID);

  operator_check_argc(0);

  const auto streamID1 = cdo_open_read(0);

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

  const auto nvars = vlistNvars(vlistID1);
  for (int varID = 0; varID < nvars; varID++) cdiDefKeyString(vlistID2, varID, CDI_KEY_UNITS, "No.");

  if (cdo_operator_f2(operatorID) == 16) vlistDefNtsteps(vlistID2, 1);

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

  const auto streamID2 = cdo_open_write(1);
  cdo_def_vlist(streamID2, vlistID2);

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

  auto gridsizemax = vlistGridsizeMax(vlistID1);
  if (vlistNumber(vlistID1) != CDI_REAL) gridsizemax *= 2;

  Field field;
  field.resize(gridsizemax);

  FieldVector2D vars1;
  fields_from_vlist(vlistID1, vars1, FIELD_VEC);

  int tsID = 0;
  int otsID = 0;
  while (true)
    {
      int nrecs = 0;
      int nsets = 0;
      while (true)
        {
          nrecs = cdo_stream_inq_timestep(streamID1, tsID);
          if (nrecs == 0) break;

          const auto vdate = taxisInqVdate(taxisID1);
          const auto vtime = taxisInqVtime(taxisID1);

          if (nsets == 0) SET_DATE(indate2, vdate, vtime);
          SET_DATE(indate1, vdate, vtime);

          if (DATE_IS_NEQ(indate1, indate2, cmplen)) break;

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

              if (tsID == 0)
                {
                  recList[recID].varID = varID;
                  recList[recID].levelID = levelID;
                  recList[recID].lconst = vlistInqVarTimetype(vlistID1, varID) == TIME_CONSTANT;
                }

              const size_t fieldsize = vars1[varID][levelID].size;

              if (nsets == 0)
                {
                  for (size_t i = 0; i < fieldsize; i++) vars1[varID][levelID].vec_d[i] = vars1[varID][levelID].missval;
                  vars1[varID][levelID].nmiss = fieldsize;
                }

              cdo_read_record(streamID1, field.vec_d.data(), &field.nmiss);
              field.size = vars1[varID][levelID].size;
              field.grid = vars1[varID][levelID].grid;
              field.missval = vars1[varID][levelID].missval;

              field2_count(vars1[varID][levelID], field);
            }

          vdate0 = vdate;
          vtime0 = vtime;
          nsets++;
          tsID++;
        }

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

      taxisDefVdate(taxisID2, vdate0);
      taxisDefVtime(taxisID2, vtime0);
      cdo_def_timestep(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;
          cdo_def_record(streamID2, varID, levelID);
          cdo_write_record(streamID2, vars1[varID][levelID].vec_d.data(), vars1[varID][levelID].nmiss);
        }

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

  cdo_stream_close(streamID2);
  cdo_stream_close(streamID1);

  cdo_finish();

  return nullptr;
}
