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

  Author: Uwe Schulzweida

*/

/*
   This module contains the following operators:

      Timstat    timrange        Time range
      Timstat    timmin          Time minimum
      Timstat    timmax          Time maximum
      Timstat    timsum          Time sum
      Timstat    timmean         Time mean
      Timstat    timavg          Time average
      Timstat    timvar          Time variance
      Timstat    timvar1         Time variance [Normalize by (n-1)]
      Timstat    timstd          Time standard deviation
      Timstat    timstd1         Time standard deviation [Normalize by (n-1)]
      Hourstat   hourrange       Hourly range
      Hourstat   hourmin         Hourly minimum
      Hourstat   hourmax         Hourly maximum
      Hourstat   hoursum         Hourly sum
      Hourstat   hourmean        Hourly mean
      Hourstat   houravg         Hourly average
      Hourstat   hourvar         Hourly variance
      Hourstat   hourvar1        Hourly variance [Normalize by (n-1)]
      Hourstat   hourstd         Hourly standard deviation
      Hourstat   hourstd1        Hourly standard deviation [Normalize by (n-1)]
      Daystat    dayrange        Daily range
      Daystat    daymin          Daily minimum
      Daystat    daymax          Daily maximum
      Daystat    daysum          Daily sum
      Daystat    daymean         Daily mean
      Daystat    dayavg          Daily average
      Daystat    dayvar          Daily variance
      Daystat    dayvar1         Daily variance [Normalize by (n-1)]
      Daystat    daystd          Daily standard deviation
      Daystat    daystd1         Daily standard deviation [Normalize by (n-1)]
      Monstat    monrange        Monthly range
      Monstat    monmin          Monthly minimum
      Monstat    monmax          Monthly maximum
      Monstat    monsum          Monthly sum
      Monstat    monmean         Monthly mean
      Monstat    monavg          Monthly average
      Monstat    monvar          Monthly variance
      Monstat    monvar1         Monthly variance [Normalize by (n-1)]
      Monstat    monstd          Monthly standard deviation
      Monstat    monstd1         Monthly standard deviation [Normalize by (n-1)]
      Yearstat   yearrange       Yearly range
      Yearstat   yearmin         Yearly minimum
      Yearstat   yearmax         Yearly maximum
      Yearstat   yearsum         Yearly sum
      Yearstat   yearmean        Yearly mean
      Yearstat   yearavg         Yearly average
      Yearstat   yearvar         Yearly variance
      Yearstat   yearvar1        Yearly variance [Normalize by (n-1)]
      Yearstat   yearstd         Yearly standard deviation
      Yearstat   yearstd1        Yearly standard deviation [Normalize by (n-1)]
*/

#include <cdi.h>

#include "cdo_options.h"
#include "cdo_vlist.h"
#include "process_int.h"
#include "datetime.h"
#include "printinfo.h"
#include "util_date.h"
#include "param_conversion.h"
#include "progress.h"

enum
{
  HOUR_LEN = 4,
  DAY_LEN = 6,
  MON_LEN = 8,
  YEAR_LEN = 10
};

static void
vlist_set_frequency(const int vlistID, const int comparelen)
{
  const char *freq = nullptr;
  // clang-format off
  if      (comparelen == DAY_LEN)  freq = "day";
  else if (comparelen == MON_LEN)  freq = "mon";
  else if (comparelen == YEAR_LEN) freq = "year";
  // clang-format on
  if (freq) cdiDefAttTxt(vlistID, CDI_GLOBAL, "frequency", (int) strlen(freq), freq);
}

static void
set_missval(Field &field, const Field &samp, int nsets, double vfrac)
{
  const auto fieldsize = field.size;
  const auto missval = field.missval;

  size_t irun = 0;
  for (size_t i = 0; i < fieldsize; ++i)
    {
      if ((samp.vec_d[i] / nsets) < vfrac)
        {
          field.vec_d[i] = missval;
          irun++;
        }
    }

  if (irun) field.nmiss = field_num_miss(field);
}

static void
addOperators(void)
{
  // clang-format off
  cdo_operator_add("timrange",   FieldFunc_Range,  DATE_LEN, nullptr);
  cdo_operator_add("timmin",     FieldFunc_Min,    DATE_LEN, nullptr);
  cdo_operator_add("timmax",     FieldFunc_Max,    DATE_LEN, nullptr);
  cdo_operator_add("timminidx",  FieldFunc_Minidx, DATE_LEN, nullptr);
  cdo_operator_add("timmaxidx",  FieldFunc_Maxidx, DATE_LEN, nullptr);
  cdo_operator_add("timsum",     FieldFunc_Sum,    DATE_LEN, nullptr);
  cdo_operator_add("timmean",    FieldFunc_Mean,   DATE_LEN, nullptr);
  cdo_operator_add("timavg",     FieldFunc_Avg,    DATE_LEN, nullptr);
  cdo_operator_add("timvar",     FieldFunc_Var,    DATE_LEN, nullptr);
  cdo_operator_add("timvar1",    FieldFunc_Var1,   DATE_LEN, nullptr);
  cdo_operator_add("timstd",     FieldFunc_Std,    DATE_LEN, nullptr);
  cdo_operator_add("timstd1",    FieldFunc_Std1,   DATE_LEN, nullptr);
  cdo_operator_add("yearrange",  FieldFunc_Range,  YEAR_LEN, nullptr);
  cdo_operator_add("yearmin",    FieldFunc_Min,    YEAR_LEN, nullptr);
  cdo_operator_add("yearmax",    FieldFunc_Max,    YEAR_LEN, nullptr);
  cdo_operator_add("yearminidx", FieldFunc_Minidx, YEAR_LEN, nullptr);
  cdo_operator_add("yearmaxidx", FieldFunc_Maxidx, YEAR_LEN, nullptr);
  cdo_operator_add("yearsum",    FieldFunc_Sum,    YEAR_LEN, nullptr);
  cdo_operator_add("yearmean",   FieldFunc_Mean,   YEAR_LEN, nullptr);
  cdo_operator_add("yearavg",    FieldFunc_Avg,    YEAR_LEN, nullptr);
  cdo_operator_add("yearvar",    FieldFunc_Var,    YEAR_LEN, nullptr);
  cdo_operator_add("yearvar1",   FieldFunc_Var1,   YEAR_LEN, nullptr);
  cdo_operator_add("yearstd",    FieldFunc_Std,    YEAR_LEN, nullptr);
  cdo_operator_add("yearstd1",   FieldFunc_Std1,   YEAR_LEN, nullptr);
  cdo_operator_add("monrange",   FieldFunc_Range,  MON_LEN, nullptr);
  cdo_operator_add("monmin",     FieldFunc_Min,    MON_LEN, nullptr);
  cdo_operator_add("monmax",     FieldFunc_Max,    MON_LEN, nullptr);
  cdo_operator_add("monsum",     FieldFunc_Sum,    MON_LEN, nullptr);
  cdo_operator_add("monmean",    FieldFunc_Mean,   MON_LEN, nullptr);
  cdo_operator_add("monavg",     FieldFunc_Avg,    MON_LEN, nullptr);
  cdo_operator_add("monvar",     FieldFunc_Var,    MON_LEN, nullptr);
  cdo_operator_add("monvar1",    FieldFunc_Var1,   MON_LEN, nullptr);
  cdo_operator_add("monstd",     FieldFunc_Std,    MON_LEN, nullptr);
  cdo_operator_add("monstd1",    FieldFunc_Std1,   MON_LEN, nullptr);
  cdo_operator_add("dayrange",   FieldFunc_Range,  DAY_LEN, nullptr);
  cdo_operator_add("daymin",     FieldFunc_Min,    DAY_LEN, nullptr);
  cdo_operator_add("daymax",     FieldFunc_Max,    DAY_LEN, nullptr);
  cdo_operator_add("daysum",     FieldFunc_Sum,    DAY_LEN, nullptr);
  cdo_operator_add("daymean",    FieldFunc_Mean,   DAY_LEN, nullptr);
  cdo_operator_add("dayavg",     FieldFunc_Avg,    DAY_LEN, nullptr);
  cdo_operator_add("dayvar",     FieldFunc_Var,    DAY_LEN, nullptr);
  cdo_operator_add("dayvar1",    FieldFunc_Var1,   DAY_LEN, nullptr);
  cdo_operator_add("daystd",     FieldFunc_Std,    DAY_LEN, nullptr);
  cdo_operator_add("daystd1",    FieldFunc_Std1,   DAY_LEN, nullptr);
  cdo_operator_add("hourrange",  FieldFunc_Range,  HOUR_LEN, nullptr);
  cdo_operator_add("hourmin",    FieldFunc_Min,    HOUR_LEN, nullptr);
  cdo_operator_add("hourmax",    FieldFunc_Max,    HOUR_LEN, nullptr);
  cdo_operator_add("hoursum",    FieldFunc_Sum,    HOUR_LEN, nullptr);
  cdo_operator_add("hourmean",   FieldFunc_Mean,   HOUR_LEN, nullptr);
  cdo_operator_add("houravg",    FieldFunc_Avg,    HOUR_LEN, nullptr);
  cdo_operator_add("hourvar",    FieldFunc_Var,    HOUR_LEN, nullptr);
  cdo_operator_add("hourvar1",   FieldFunc_Var1,   HOUR_LEN, nullptr);
  cdo_operator_add("hourstd",    FieldFunc_Std,    HOUR_LEN, nullptr);
  cdo_operator_add("hourstd1",   FieldFunc_Std1,   HOUR_LEN, nullptr);
  // clang-format on
}

void *
Timstat(void *argument)
{
  const TimeStat timestat_date = TimeStat::MEAN;
  int64_t vdate0 = 0;
  int vtime0 = 0;
  CdoStreamID streamID3;
  int vlistID3, taxisID3 = -1;
  bool lvfrac = false;
  char indate1[DATE_LEN + 1], indate2[DATE_LEN + 1];
  double vfrac = 1;

  cdo_initialize(argument);

  addOperators();

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

  const auto lminidx = (operfunc == FieldFunc_Minidx);
  const auto lmaxidx = (operfunc == FieldFunc_Maxidx);
  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 || lminidx || lmaxidx);
  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;

  if (operfunc == FieldFunc_Mean)
    {
      const auto oargc = cdo_operator_argc();
      if (oargc == 1)
        {
          lvfrac = true;
          vfrac = parameter_to_double(cdo_operator_argv(0));
          if (Options::cdoVerbose) cdo_print("Set vfrac to %g", vfrac);
          if (vfrac < 0 || vfrac > 1) cdo_abort("vfrac out of range!");
        }
      else if (oargc > 1)
        cdo_abort("Too many arguments!");
    }
  else
    {
      operator_check_argc(0);
    }

  const int cmplen = DATE_LEN - comparelen;

  const auto streamID1 = cdo_open_read(0);

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

  vlist_define_timestep_type(vlistID2, operfunc);

  vlistDefNtsteps(vlistID2, (cmplen == 0) ? 1 : -1);

  const auto taxisID1 = vlistInqTaxis(vlistID1);
  const auto taxisID2 = taxisDuplicate(taxisID1);
  taxisWithBounds(taxisID2);
  if (taxisInqType(taxisID2) == TAXIS_FORECAST) taxisDefType(taxisID2, TAXIS_RELATIVE);
  vlistDefTaxis(vlistID2, taxisID2);

  const auto nvars = vlistNvars(vlistID1);

  if (lminidx || lmaxidx)
    for (int varID = 0; varID < nvars; ++varID) vlistDefVarDatatype(vlistID2, varID, CDI_DATATYPE_INT32);

  vlist_set_frequency(vlistID2, comparelen);

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

  if (Options::cdoDiag)
    {
      char filename[8192];
      strcpy(filename, cdo_operator_name(operatorID));
      strcat(filename, "_");
      strcat(filename, cdo_get_stream_name(1));
      streamID3 = cdo_open_write(filename);

      vlistID3 = vlistDuplicate(vlistID1);

      for (int varID = 0; varID < nvars; ++varID)
        {
          vlistDefVarDatatype(vlistID3, varID, CDI_DATATYPE_INT32);
          vlistDefVarMissval(vlistID3, varID, -1);
          cdiDefKeyString(vlistID3, varID, CDI_KEY_UNITS, "");
          vlistDefVarAddoffset(vlistID3, varID, 0);
          vlistDefVarScalefactor(vlistID3, varID, 1);
        }

      taxisID3 = taxisDuplicate(taxisID1);
      taxisWithBounds(taxisID3);
      vlistDefTaxis(vlistID3, taxisID3);

      cdo_def_vlist(streamID3, vlistID3);
    }

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

  DateTimeList dtlist;
  dtlist.set_stat(timestat_date);
  dtlist.set_calendar(taxisInqCalendar(taxisID1));

  VarList varList;
  varListInit(varList, vlistID1);

  int VARS_MEMTYPE = 0;
  if ((operfunc == FieldFunc_Min) || (operfunc == FieldFunc_Max)) VARS_MEMTYPE = FIELD_NAT;
  // if ((Options::CDO_???(--single) == MemType::Float) && (operfunc == FieldFunc_Mean)) VARS_MEMTYPE = FIELD_NAT;
  // if (Options::CDO_Memtype == MemType::Float) VARS_MEMTYPE = FIELD_FLT;
  if (Options::cdoDiag || (lvfrac && operfunc == FieldFunc_Mean)) VARS_MEMTYPE = FIELD_DBL;

  Field field;
  Varray<double> samp;

  FieldVector2D samp1, vars1, vars2;
  fields_from_vlist(vlistID1, samp1);
  fields_from_vlist(vlistID1, vars1, FIELD_VEC | VARS_MEMTYPE);
  if (lvars2) fields_from_vlist(vlistID1, vars2, FIELD_VEC);

  const auto ntsteps1 = vlistNtsteps(vlistID1);

  if (!Options::cdoVerbose && ntsteps1 > 1) progress::init();

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

          if (!Options::cdoVerbose && ntsteps1 > 1) progress::update(0, 1, (tsID + 1.0) / ntsteps1);

          dtlist.taxis_inq_timestep(taxisID1, nsets);
          const auto vdate = dtlist.get_vdate(nsets);
          const auto vtime = dtlist.get_vtime(nsets);

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

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

              if (nsets == 0)
                {
                  cdo_read_record(streamID1, rvars1);
                  if (lrange || lminidx || lmaxidx)
                    {
                      vars2[varID][levelID].nmiss = rvars1.nmiss;
                      vars2[varID][levelID].vec_d = rvars1.vec_d;
                    }

                  if (lminidx || lmaxidx) field_fill(rvars1, 0.0);

                  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[varID][levelID], field);
                  else if (lrange)  field2_maxmin(rvars1, vars2[varID][levelID], field);
                  else if (lminidx) field2_minidx(rvars1, vars2[varID][levelID], field, nsets);
                  else if (lmaxidx) field2_maxidx(rvars1, vars2[varID][levelID], field, nsets);
                  else              field2_function(rvars1, field, operfunc);
                  // clang-format on
                }
            }

          if (nsets == 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[varID][levelID], vars1[varID][levelID]);
              }

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

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

      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[varID][levelID];
          auto &rvars1 = vars1[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[varID][levelID], rsamp1, divisor);
              else
                fieldc_stdvar_func(rvars1, vars2[varID][levelID], nsets, divisor);
            }
          else if (lrange)
            {
              field2_sub(rvars1, vars2[varID][levelID]);
            }
        }

      if (Options::cdoVerbose)
        cdo_print("%s %s  vfrac = %g, nsets = %d", date_to_string(vdate0).c_str(), time_to_string(vtime0).c_str(), vfrac, nsets);

      if (lvfrac && operfunc == FieldFunc_Mean)
        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[varID][levelID];

            if (!rsamp1.empty()) set_missval(vars1[varID][levelID], rsamp1, nsets, vfrac);
          }

      dtlist.stat_taxis_def_timestep(taxisID2, nsets);
      cdo_def_timestep(streamID2, otsID);

      if (Options::cdoDiag)
        {
          dtlist.stat_taxis_def_timestep(taxisID3, nsets);
          cdo_def_timestep(streamID3, 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];

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

          if (Options::cdoDiag)
            {
              auto &rsamp1 = samp1[varID][levelID];
              samp.resize(field.size);
              if (!rsamp1.empty())
                samp = rsamp1.vec_d;
              else
                varray_fill(samp, (double)nsets);

              cdo_def_record(streamID3, varID, levelID);
              cdo_write_record(streamID3, samp.data(), 0);
            }
        }

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

  if (!Options::cdoVerbose && ntsteps1 > 1) progress::update(0, 1, 1);

  if (Options::cdoDiag) cdo_stream_close(streamID3);
  cdo_stream_close(streamID2);
  cdo_stream_close(streamID1);

  cdo_finish();

  return nullptr;
}
