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

  Copyright (C) 2003-2021 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 "process_int.h"
#include "param_conversion.h"
#include "pmlist.h"

int yearMode = 0;

static void
setParameter(void)
{
  const auto pargc = cdo_operator_argc();
  if (pargc)
    {
      auto pargv = cdo_get_oper_argv();

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

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

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

static void
addOperators(void)
{
  // clang-format off
  cdo_operator_add("ydayrange", FieldFunc_Range, 0, nullptr);
  cdo_operator_add("ydaymin",   FieldFunc_Min,   0, nullptr);
  cdo_operator_add("ydaymax",   FieldFunc_Max,   0, nullptr);
  cdo_operator_add("ydaysum",   FieldFunc_Sum,   0, nullptr);
  cdo_operator_add("ydaymean",  FieldFunc_Mean,  0, nullptr);
  cdo_operator_add("ydayavg",   FieldFunc_Avg,   0, nullptr);
  cdo_operator_add("ydayvar",   FieldFunc_Var,   0, nullptr);
  cdo_operator_add("ydayvar1",  FieldFunc_Var1,  0, nullptr);
  cdo_operator_add("ydaystd",   FieldFunc_Std,   0, nullptr);
  cdo_operator_add("ydaystd1",  FieldFunc_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];

  cdo_initialize(process);

  setParameter();

  addOperators();

  const auto operatorID = cdo_operator_id();
  const auto operfunc = cdo_operator_f1(operatorID);

  const auto lrange = (operfunc == FieldFunc_Range);
  const auto lmean = (operfunc == FieldFunc_Mean || operfunc == FieldFunc_Avg);
  const auto lstd = (operfunc == FieldFunc_Std || operfunc == FieldFunc_Std1);
  const auto lvarstd = (lstd || operfunc == FieldFunc_Var || operfunc == FieldFunc_Var1);
  const auto lvars2 = (lvarstd || lrange);
  const int divisor = (operfunc == FieldFunc_Std1 || operfunc == FieldFunc_Var1);

  auto field2_stdvar_func = lstd ? field2_std : field2_var;
  auto fieldc_stdvar_func = lstd ? fieldc_std : fieldc_var;

  const auto streamID1 = cdo_open_read(0);

  const auto vlistID1 = cdo_stream_inq_vlist(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 = cdo_open_write(1);
  cdo_def_vlist(streamID2, vlistID2);

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

  VarList varList;
  varListInit(varList, vlistID1);

  int VARS_MEMTYPE = 0;
  if ((operfunc == FieldFunc_Min) || (operfunc == FieldFunc_Max)) VARS_MEMTYPE = FIELD_NAT;

  Field field;

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

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

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

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

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

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

      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 = (varList[varID].timetype == TIME_CONSTANT);
            }

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

          const auto nsets = dayoy_nsets[dayoy];

          if (nsets == 0)
            {
              cdo_read_record(streamID1, rvars1);
              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(rvars1.size);
                  field2_vinit(rsamp1, rvars1);
                }
            }
          else
            {
              field.init(varList[varID]);
              cdo_read_record(streamID1, field);

              if (field.nmiss || !rsamp1.empty())
                {
                  if (rsamp1.empty()) rsamp1.resize(rvars1.size, nsets);
                  field2_vincr(rsamp1, field);
                }

              // clang-format off
              if      (lvarstd) field2_sumsumq(rvars1, vars2[dayoy][varID][levelID], field);
              else if (lrange)  field2_maxmin(rvars1, vars2[dayoy][varID][levelID], field);
              else              field2_function(rvars1, field, operfunc);
              // clang-format on
            }
        }

      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;
            field2_moq(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;
            const auto &rsamp1 = samp1[dayoy][varID][levelID];
            auto &rvars1 = vars1[dayoy][varID][levelID];

            if (lmean)
              {
                if (!rsamp1.empty())
                  field2_div(rvars1, rsamp1);
                else
                  fieldc_div(rvars1, (double) nsets);
              }
            else if (lvarstd)
              {
                if (!rsamp1.empty())
                  field2_stdvar_func(rvars1, vars2[dayoy][varID][levelID], rsamp1, divisor);
                else
                  fieldc_stdvar_func(rvars1, vars2[dayoy][varID][levelID], nsets, divisor);
              }
            else if (lrange)
              {
                field2_sub(rvars1, vars2[dayoy][varID][levelID]);
              }
          }

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

            cdo_def_record(streamID2, varID, levelID);
            cdo_write_record(streamID2, rvars1);
          }

        otsID++;
      }

  cdo_stream_close(streamID2);
  cdo_stream_close(streamID1);

  cdo_finish();

  return nullptr;
}
