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

   Yhourstat     yhourmin        Multi-year hourly minimum
   Yhourstat     yhourmax        Multi-year hourly maximum
   Yhourstat     yhourrange      Multi-year hourly range
   Yhourstat     yhoursum        Multi-year hourly sum
   Yhourstat     yhourmean       Multi-year hourly mean
   Yhourstat     yhouravg        Multi-year hourly average
   Yhourstat     yhourstd        Multi-year hourly standard deviation
   Yhourstat     yhourstd1       Multi-year hourly standard deviation (n-1)
   Yhourstat     yhourvar        Multi-year hourly variance
   Yhourstat     yhourvar1       Multi-year hourly variance (n-1)

   Dhourstat     dhourmin        Multi-day hourly minimum
   Dhourstat     dhourmax        Multi-day hourly maximum
   Dhourstat     dhourrange      Multi-day hourly range
   Dhourstat     dhoursum        Multi-day hourly sum
   Dhourstat     dhourmean       Multi-day hourly mean
   Dhourstat     dhouravg        Multi-day hourly average
   Dhourstat     dhourstd        Multi-day hourly standard deviation
   Dhourstat     dhourstd1       Multi-day hourly standard deviation (n-1)
   Dhourstat     dhourvar        Multi-day hourly variance
   Dhourstat     dhourvar1       Multi-day hourly variance (n-1)
*/

#include <cdi.h>

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

static void
addOperators(void)
{
  // clang-format off
  cdoOperatorAdd("yhourrange", func_range, 0, nullptr);
  cdoOperatorAdd("yhourmin",   func_min,   0, nullptr);
  cdoOperatorAdd("yhourmax",   func_max,   0, nullptr);
  cdoOperatorAdd("yhoursum",   func_sum,   0, nullptr);
  cdoOperatorAdd("yhourmean",  func_mean,  0, nullptr);
  cdoOperatorAdd("yhouravg",   func_avg,   0, nullptr);
  cdoOperatorAdd("yhourvar",   func_var,   0, nullptr);
  cdoOperatorAdd("yhourvar1",  func_var1,  0, nullptr);
  cdoOperatorAdd("yhourstd",   func_std,   0, nullptr);
  cdoOperatorAdd("yhourstd1",  func_std1,  0, nullptr);

  cdoOperatorAdd("dhourrange", func_range, 0, nullptr);
  cdoOperatorAdd("dhourmin",   func_min,   1, nullptr);
  cdoOperatorAdd("dhourmax",   func_max,   1, nullptr);
  cdoOperatorAdd("dhoursum",   func_sum,   1, nullptr);
  cdoOperatorAdd("dhourmean",  func_mean,  1, nullptr);
  cdoOperatorAdd("dhouravg",   func_avg,   1, nullptr);
  cdoOperatorAdd("dhourvar",   func_var,   1, nullptr);
  cdoOperatorAdd("dhourvar1",  func_var1,  1, nullptr);
  cdoOperatorAdd("dhourstd",   func_std,   1, nullptr);
  cdoOperatorAdd("dhourstd1",  func_std1,  1, nullptr);
  // clang-format on
}

void *
Yhourstat(void *process)
{
  TimeStat timestat_date = TimeStat::LAST;

  cdoInitialize(process);

  addOperators();

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

  const bool ldaily = cdoOperatorF2(operatorID) == 1;

  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;

  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);
  if (taxisInqType(taxisID2) == TAXIS_FORECAST) taxisDefType(taxisID2, TAXIS_RELATIVE);

  const int MaxHours = ldaily ? 25 : 9301;     // year: 31*12*25 + 1
  std::vector<int> hourot_nsets(MaxHours, 0);  // hour of time
  FieldVector3D vars1(MaxHours), vars2(MaxHours), samp1(MaxHours);

  std::vector<DateTimeList> dtlist(MaxHours);
  for (int hourot = 0; hourot < MaxHours; ++hourot)
    {
      dtlist[hourot].setStat(timestat_date);
      dtlist[hourot].setCalendar(taxisInqCalendar(taxisID1));
    }

  vlistDefTaxis(vlistID2, taxisID2);

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

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

  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 hourot = ldaily ? decodeHourOfDay(vdate, vtime) : decodeHourOfYear(vdate, vtime);
      if (hourot < 0 || hourot >= MaxHours)
        cdoAbort("Hour of year %d out of range (%s %s)!", hourot, dateToString(vdate).c_str(), timeToString(vtime).c_str());

      dtlist[hourot].taxisInqTimestep(taxisID1, hourot_nsets[hourot]);

      if (!vars1[hourot].size())
        {
          fieldsFromVlist(vlistID1, samp1[hourot]);
          fieldsFromVlist(vlistID1, vars1[hourot], FIELD_VEC);
          if (lvars2) fieldsFromVlist(vlistID1, vars2[hourot], 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 = vlistInqVarTimetype(vlistID1, varID) == TIME_CONSTANT;
            }

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

          const auto nsets = hourot_nsets[hourot];
          const auto fieldsize = rvars1.size;

          if (nsets == 0)
            {
              cdoReadRecord(streamID1, rvars1.vec_d.data(), &rvars1.nmiss);
              if (lrange)
                {
                  vars2[hourot][varID][levelID].nmiss = rvars1.nmiss;
                  vars2[hourot][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[hourot][varID][levelID], field);
                  vfarsum(rvars1, field);
                }
              else if (lrange)
                {
                  vfarmin(vars2[hourot][varID][levelID], field);
                  vfarmax(rvars1, field);
                }
              else
                {
                  vfarfun(rvars1, field, operfunc);
                }
            }
        }

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

      hourot_nsets[hourot]++;
      tsID++;
    }

  for (int hourot = 0; hourot < MaxHours; ++hourot)
    if (hourot_nsets[hourot])
      {
        const auto nsets = hourot_nsets[hourot];
        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[hourot][varID][levelID];
            auto &rvars1 = vars1[hourot][varID][levelID];

            if (lmean)
              {
                if (!rsamp1.empty())
                  vfardiv(rvars1, rsamp1);
                else
                  vfarcdiv(rvars1, (double) nsets);
              }
            else if (lvarstd)
              {
                auto &rvars2 = vars2[hourot][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[hourot][varID][levelID];
                vfarsub(rvars1, rvars2);
              }
          }

        dtlist[hourot].statTaxisDefTimestep(taxisID2, hourot_nsets[hourot]);
        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[hourot][varID][levelID];

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

        otsID++;
      }

  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  cdoFinish();

  return nullptr;
}
