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

  Author: Uwe Schulzweida

*/

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <cdi.h>

#include "process_int.h"
#include "cdo_vlist.h"
#include "param_conversion.h"
#include "cdo_options.h"
#include "cimdOmp.h"
#include "field_functions.h"
#include "pmlist.h"
#include "fill_1d.h"

class ModuleVertfillmiss
{
private:
  CdoStreamID streamID1;
  CdoStreamID streamID2;
  int vlistID1;
  int vlistID2;

  int taxisID1;
  int taxisID2;

  VarList varList;
  FieldVector2D vars;

  int calendar;
  int nvars;

  FillMethod method{ FillMethod::Nearest };
  int limit{ 0 };
  int maxGaps{ 0 };

  Varray2D<double> dataValues2D;
  Varray<double> levelValues;

  void
  add_operators()
  {
    cdo_operator_add("vertfillmiss", 0, 0, nullptr);
  }

  FillMethod
  convert_fillmethod(const std::string &methodStr)
  {
    auto fillMethod = string_to_fillmethod(methodStr);

    if (fillMethod == FillMethod::Undefined) cdo_abort("method=%s unsupported!", methodStr);

    return fillMethod;
  }

  void
  get_parameter()
  {
    auto pargc = cdo_operator_argc();
    if (pargc)
      {
        const auto &pargv = cdo_get_oper_argv();

        KVList kvlist;
        kvlist.name = cdo_module_name();
        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);
            if (kv.nvalues < 1) cdo_abort("Missing value for parameter key >%s<!", key);
            const auto &value = kv.values[0];

            // clang-format off
            if      (key == "method")   method = convert_fillmethod(parameter_to_word(value));
            else if (key == "limit")    limit = parameter_to_int(value);
            else if (key == "max_gaps") maxGaps = parameter_to_int(value);
            else cdo_abort("Invalid parameter key >%s<!", key);
            // clang-format on
          }
      }
  }

public:
  void
  init(void *process)
  {
    cdo_initialize(process);

    add_operators();

    get_parameter();
    limit = std::max(limit, 0);
    maxGaps = std::max(maxGaps, 0);

    streamID1 = cdo_open_read(0);
    streamID2 = cdo_open_write(1);

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

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

    cdo_def_vlist(streamID2, vlistID2);

    calendar = taxisInqCalendar(taxisID1);

    varList_init(varList, vlistID1);

    nvars = vlistNvars(vlistID1);

    int maxLevels = 0;
    for (auto &var : varList) maxLevels = std::max(maxLevels, var.nlevels);

    dataValues2D = Varray2D<double>(Threading::ompNumThreads);
    for (auto &dataValues : dataValues2D) dataValues.resize(maxLevels);

    levelValues.resize(maxLevels);

    fields_from_vlist(vlistID1, vars);
  }

  void
  fillmiss(int varID)
  {
    const auto &var = varList[varID];
    auto fieldMemType = var.memType;
    auto gridsize = var.gridsize;
    auto numLevels = var.nlevels;
    auto missval = var.missval;

    zaxisInqLevels(var.zaxisID, levelValues.data());

#ifdef _OPENMP
#pragma omp parallel for default(shared) schedule(static)
#endif
    for (size_t i = 0; i < gridsize; ++i)
      {
        auto ompthID = cdo_omp_get_thread_num();
        auto &dataValues = dataValues2D[ompthID];

        if (fieldMemType == MemType::Float)
          for (int levelID = 0; levelID < numLevels; ++levelID) dataValues[levelID] = vars[varID][levelID].vec_f[i];
        else
          for (int levelID = 0; levelID < numLevels; ++levelID) dataValues[levelID] = vars[varID][levelID].vec_d[i];

        if (method == FillMethod::Nearest)
          fill_1d_nearest(numLevels, levelValues, dataValues, missval, limit, maxGaps);
        else if (method == FillMethod::Linear)
          fill_1d_linear(numLevels, levelValues, dataValues, missval, limit, maxGaps);
        else if (method == FillMethod::Forward)
          fill_1d_forward(numLevels, dataValues, missval, limit, maxGaps);
        else if (method == FillMethod::Backward)
          fill_1d_backward(numLevels, dataValues, missval, limit, maxGaps);

        if (fieldMemType == MemType::Float)
          for (int levelID = 0; levelID < numLevels; ++levelID) vars[varID][levelID].vec_f[i] = dataValues[levelID];
        else
          for (int levelID = 0; levelID < numLevels; ++levelID) vars[varID][levelID].vec_d[i] = dataValues[levelID];
      }
  }

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

        cdo_taxis_copy_timestep(taxisID2, taxisID1);
        cdo_def_timestep(streamID2, tsID);

        for (int recID = 0; recID < nrecs; ++recID)
          {
            int varID, levelID;
            cdo_inq_record(streamID1, &varID, &levelID);
            auto &field = vars[varID][levelID];
            field.init(varList[varID]);
            cdo_read_record(streamID1, field);
          }

        for (int varID = 0; varID < nvars; ++varID)
          {
            int numLevels = varList[varID].nlevels;
            if (numLevels > 1)
              {
                size_t numMissVals = 0;
                for (int levelID = 0; levelID < numLevels; ++levelID) { numMissVals += vars[varID][levelID].nmiss; }
                if (numMissVals > 0) fillmiss(varID);
              }
          }

        for (int varID = 0; varID < nvars; ++varID)
          {
            for (int levelID = 0; levelID < varList[varID].nlevels; ++levelID)
              {
                auto &field = vars[varID][levelID];
                if (field.hasData())
                  {
                    cdo_def_record(streamID2, varID, levelID);
                    field_num_mv(field);
                    cdo_write_record(streamID2, field);
                  }
              }
          }

        tsID++;
      }
  }

  void
  close()
  {
    cdo_stream_close(streamID2);
    cdo_stream_close(streamID1);

    cdo_finish();
  }
};

void *
Vertfillmiss(void *process)
{
  ModuleVertfillmiss verfillmiss;
  verfillmiss.init(process);
  verfillmiss.run();
  verfillmiss.close();

  return nullptr;
}
