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

      Ydaystat   ydayrange       Multi-year daily range
      Ydaystat   ydaymin         Multi-year daily minimum
      Ydaystat   ydaymax         Multi-year daily maximum
      Ydaystat   ydaysum         Multi-year daily sum
      Ydaystat   ydaymean        Multi-year daily mean
      Ydaystat   ydayavg         Multi-year daily average
      Ydaystat   ydayvar         Multi-year daily variance
      Ydaystat   ydayvar1        Multi-year daily variance [Normalize by (n-1)]
      Ydaystat   ydaystd         Multi-year daily standard deviation
      Ydaystat   ydaystd1        Multi-year daily standard deviation [Normalize by (n-1)]
*/

#include <cdi.h>

#include "cdo_options.h"
#include "cdo_vlist.h"
#include "datetime.h"
#include "functs.h"
#include "process_int.h"
#include "param_conversion.h"
#include "pmlist.h"

int yearMode = 0;

static void
setParameter(void)
{
  const auto pargc = operatorArgc();
  if (pargc)
    {
      auto pargv = cdoGetOperArgv();

      KVList kvlist;
      kvlist.name = "YDAYSTAT";
      if (kvlist.parseArguments(pargc, pargv) != 0) cdoAbort("Parse error!");
      if (Options::cdoVerbose) kvlist.print();

      for (const auto &kv : kvlist)
        {
          const auto &key = kv.key;
          if (kv.nvalues > 1) cdoAbort("Too many values for parameter key >%s<!", key.c_str());
          if (kv.nvalues < 1) cdoAbort("Missing value for parameter key >%s<!", key.c_str());
          const auto &value = kv.values[0];

          if (key == "yearMode")
            yearMode = parameter2int(value);
          else
            cdoAbort("Invalid parameter key >%s<!", key.c_str());
        }
    }
}

static void
addOperators(void)
{
  // clang-format off
  cdoOperatorAdd("ydayrange", func_range, 0, nullptr);
  cdoOperatorAdd("ydaymin",   func_min,   0, nullptr);
  cdoOperatorAdd("ydaymax",   func_max,   0, nullptr);
  cdoOperatorAdd("ydaysum",   func_sum,   0, nullptr);
  cdoOperatorAdd("ydaymean",  func_mean,  0, nullptr);
  cdoOperatorAdd("ydayavg",   func_avg,   0, nullptr);
  cdoOperatorAdd("ydayvar",   func_var,   0, nullptr);
  cdoOperatorAdd("ydayvar1",  func_var1,  0, nullptr);
  cdoOperatorAdd("ydaystd",   func_std,   0, nullptr);
  cdoOperatorAdd("ydaystd1",  func_std1,  0, nullptr);
  // clang-format on
}

void *
Ydaystat(void *process)
{
  constexpr int MaxDays = 373;
  int dayoy_nsets[MaxDays] = { 0 };
  int64_t vdates[MaxDays] = { 0 };
  int vtimes[MaxDays] = { 0 };
  FieldVector2D vars1[MaxDays], vars2[MaxDays], samp1[MaxDays];

  cdoInitialize(process);

  setParameter();

  addOperators();

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

  const bool lrange = operfunc == func_range;
  const bool lmean = operfunc == func_mean || operfunc == func_avg;
  const bool lstd = operfunc == func_std || operfunc == func_std1;
  const bool lvarstd = operfunc == func_std || operfunc == func_var || operfunc == func_std1 || operfunc == func_var1;
  const int divisor = operfunc == func_std1 || operfunc == func_var1;
  const bool lvars2 = lvarstd || lrange;

  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);
  if (taxisHasBounds(taxisID2)) taxisDeleteBounds(taxisID2);
  vlistDefTaxis(vlistID2, taxisID2);

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

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

  VarList varList1;
  varListInit(varList1, vlistID1);

  const auto gridsizemax = vlistGridsizeMax(vlistID1);

  Field field;
  field.resize(gridsizemax);

  int tsID = 0;
  int otsID = 0;
  while (true)
    {
      const auto nrecs = cdoStreamInqTimestep(streamID1, tsID);
      if (nrecs == 0) break;

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

      if (Options::cdoVerbose) cdoPrint("process timestep: %d %d %d", tsID + 1, vdate, vtime);

      const auto dayoy = decodeDayOfYear(vdate);
      if (dayoy < 0 || dayoy >= MaxDays) cdoAbort("Day of year %d out of range (date=%d)!", dayoy, vdate);

      vdates[dayoy] = vdate;
      vtimes[dayoy] = vtime;

      if (!vars1[dayoy].size())
        {
          fieldsFromVlist(vlistID1, samp1[dayoy]);
          fieldsFromVlist(vlistID1, vars1[dayoy], FIELD_VEC);
          if (lvars2) fieldsFromVlist(vlistID1, vars2[dayoy], FIELD_VEC);
        }

      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[dayoy][varID][levelID];
          auto &rvars1 = vars1[dayoy][varID][levelID];

          const auto nsets = dayoy_nsets[dayoy];
          const auto fieldsize = rvars1.size;

          if (nsets == 0)
            {
              cdoReadRecord(streamID1, rvars1.vec_d.data(), &rvars1.nmiss);
              if (lrange)
                {
                  vars2[dayoy][varID][levelID].nmiss = rvars1.nmiss;
                  vars2[dayoy][varID][levelID].vec_d = rvars1.vec_d;
                }

              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);
                }
            }
          else
            {
              cdoReadRecord(streamID1, field.vec_d.data(), &field.nmiss);
              field.size = fieldsize;
              field.grid = rvars1.grid;
              field.missval = rvars1.missval;

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

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

              if (lvarstd)
                {
                  vfarsumq(vars2[dayoy][varID][levelID], field);
                  vfarsum(rvars1, field);
                }
              else if (lrange)
                {
                  vfarmin(vars2[dayoy][varID][levelID], field);
                  vfarmax(rvars1, field);
                }
              else
                {
                  vfarfun(rvars1, field, operfunc);
                }
            }
        }

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

            const auto varID = recList[recID].varID;
            const auto levelID = recList[recID].levelID;
            vfarmoq(vars2[dayoy][varID][levelID], vars1[dayoy][varID][levelID]);
          }

      dayoy_nsets[dayoy]++;
      tsID++;
    }

  // set the year to the minimum of years found on output timestep
  if (yearMode)
    {
      int year, month, day;
      int outyear = 1e9;
      for (int dayoy = 0; dayoy < MaxDays; dayoy++)
        if (dayoy_nsets[dayoy])
          {
            cdiDecodeDate(vdates[dayoy], &year, &month, &day);
            if (year < outyear) outyear = year;
          }
      for (int dayoy = 0; dayoy < MaxDays; dayoy++)
        if (dayoy_nsets[dayoy])
          {
            cdiDecodeDate(vdates[dayoy], &year, &month, &day);
            if (year > outyear) vdates[dayoy] = cdiEncodeDate(outyear, month, day);
            //  printf("vdates[%d] = %d  nsets = %d\n", dayoy, vdates[dayoy], nsets[dayoy]);
          }
    }

  for (int dayoy = 0; dayoy < MaxDays; dayoy++)
    if (dayoy_nsets[dayoy])
      {
        const auto nsets = dayoy_nsets[dayoy];
        for (int recID = 0; recID < maxrecs; recID++)
          {
            if (recList[recID].lconst) continue;

            const auto varID = recList[recID].varID;
            const auto levelID = recList[recID].levelID;
            auto &rsamp1 = samp1[dayoy][varID][levelID];
            auto &rvars1 = vars1[dayoy][varID][levelID];

            if (lmean)
              {
                if (!rsamp1.empty())
                  vfardiv(rvars1, rsamp1);
                else
                  vfarcdiv(rvars1, (double) nsets);
              }
            else if (lvarstd)
              {
                auto &rvars2 = vars2[dayoy][varID][levelID];
                if (!rsamp1.empty())
                  {
                    if (lstd)
                      vfarstd(rvars1, rvars2, rsamp1, divisor);
                    else
                      vfarvar(rvars1, rvars2, rsamp1, divisor);
                  }
                else
                  {
                    if (lstd)
                      vfarcstd(rvars1, rvars2, nsets, divisor);
                    else
                      vfarcvar(rvars1, rvars2, nsets, divisor);
                  }
              }
            else if (lrange)
              {
                auto &rvars2 = vars2[dayoy][varID][levelID];
                vfarsub(rvars1, rvars2);
              }
          }

        taxisDefVdate(taxisID2, vdates[dayoy]);
        taxisDefVtime(taxisID2, vtimes[dayoy]);
        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[dayoy][varID][levelID];

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

        otsID++;
      }

  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  cdoFinish();

  return nullptr;
}
