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

  Copyright (C) 2006 Brockmann Consult

  Author: Ralf Quast
          Uwe Schulzweida

*/

/*
   This module contains the following operators:

      Timselpctl    timselpctl         Time range percentiles
*/

#include <cdi.h>

#include "cdo_options.h"
#include "process_int.h"
#include "cdo_vlist.h"
#include "param_conversion.h"
#include "percentiles_hist.h"
#include "datetime.h"
#include "field_functions.h"

class ModuleTimselpctl
{

  CdoStreamID streamID1;
  int taxisID1;

  CdoStreamID streamID2;
  int taxisID2;

  CdoStreamID streamID3;
  int taxisID3;

  CdoStreamID streamID4;
  int taxisID4;

  int noffset = 0, nskip = 0;
  int ndates;
  int maxrecs;

  double pn;

  std::vector<RecordInfo> recList;
  FieldVector constFields;
  DateTimeList dtlist;
  Field field1, field2;
  VarList varList1;
  HistogramSet hset;

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

    cdo_operator_add("timselpctl", FieldFunc_Pctl, 0, nullptr);

    operator_input_arg("percentile number, numSets <,noffset <,nskip>>");

    auto nargc = cdo_operator_argc();
    if (nargc < 2) cdo_abort("Too few arguments! Need %d found %d.", 2, nargc);

    pn = parameter_to_double(cdo_operator_argv(0));
    ndates = parameter_to_int(cdo_operator_argv(1));
    if (nargc > 2) noffset = parameter_to_int(cdo_operator_argv(2));
    if (nargc > 3) nskip = parameter_to_int(cdo_operator_argv(3));

    if (Options::cdoVerbose) cdo_print("numSets = %d, noffset = %d, nskip = %d", ndates, noffset, nskip);

    streamID1 = cdo_open_read(0);
    streamID2 = cdo_open_read(1);
    streamID3 = cdo_open_read(2);

    auto vlistID1 = cdo_stream_inq_vlist(streamID1);
    auto vlistID2 = cdo_stream_inq_vlist(streamID2);
    auto vlistID3 = cdo_stream_inq_vlist(streamID3);
    auto vlistID4 = vlistDuplicate(vlistID1);

    vlist_unpack(vlistID4);

    vlist_compare(vlistID1, vlistID2, CmpVlist::All);
    vlist_compare(vlistID1, vlistID3, CmpVlist::All);

    taxisID1 = vlistInqTaxis(vlistID1);
    taxisID2 = vlistInqTaxis(vlistID2);
    taxisID3 = vlistInqTaxis(vlistID3);
    // TODO - check that time axes 2 and 3 are equal

    taxisID4 = taxisDuplicate(taxisID1);
    taxisWithBounds(taxisID4);
    vlistDefTaxis(vlistID4, taxisID4);

    streamID4 = cdo_open_write(3);
    cdo_def_vlist(streamID4, vlistID4);

    auto ntsteps = vlistNtsteps(vlistID1);
    auto nvars = vlistNvars(vlistID1);

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

    constFields = FieldVector(maxrecs);

    dtlist.set_stat(TimeStat::MEAN);
    dtlist.set_calendar(taxisInqCalendar(taxisID1));

    varList_init(varList1, vlistID1);

    hset = HistogramSet(nvars, ntsteps);

    for (int varID = 0; varID < nvars; ++varID) hset.createVarLevels(varID, varList1[varID].nlevels, varList1[varID].gridsize);
  }

  void
  run()
  {
    int tsID;
    for (tsID = 0; tsID < noffset; ++tsID)
      {
        auto nrecs = cdo_stream_inq_timestep(streamID1, tsID);
        if (nrecs == 0) break;

        for (int recID = 0; recID < nrecs; ++recID)
          {
            int varID, levelID;
            cdo_inq_record(streamID1, &varID, &levelID);

            if (tsID == 0) recList[recID].set(varID, levelID);
          }
      }
    int otsID = 0;
    if (tsID < noffset)
      {
        cdo_warning("noffset is larger than number of timesteps!");
        return;
      }

    while (true)
      {
        auto nrecs = cdo_stream_inq_timestep(streamID2, otsID);
        if (nrecs != cdo_stream_inq_timestep(streamID3, otsID))
          cdo_abort("Number of records at time step %d of %s and %s differ!", otsID + 1, cdo_get_stream_name(1),
                    cdo_get_stream_name(2));

        auto vDateTime2 = taxisInqVdatetime(taxisID2);
        auto vDateTime3 = taxisInqVdatetime(taxisID3);
        if (cdiDateTime_isNE(vDateTime2, vDateTime3))
          cdo_abort("Verification dates at time step %d of %s and %s differ!", otsID + 1, cdo_get_stream_name(1),
                    cdo_get_stream_name(2));

        for (int recID = 0; recID < nrecs; ++recID)
          {
            int varID, levelID;
            cdo_inq_record(streamID2, &varID, &levelID);
            field1.init(varList1[varID]);
            cdo_read_record(streamID2, field1);

            cdo_inq_record(streamID3, &varID, &levelID);
            field2.init(varList1[varID]);
            cdo_read_record(streamID3, field2);

            hset.defVarLevelBounds(varID, levelID, field1, field2);
          }

        int numSets = 0;
        if (nrecs)
          for (numSets = 0; numSets < ndates; numSets++)
            {
              nrecs = cdo_stream_inq_timestep(streamID1, tsID);
              if (nrecs == 0) break;

              dtlist.taxis_inq_timestep(taxisID1, numSets);

              for (int recID = 0; recID < nrecs; ++recID)
                {
                  int varID, levelID;
                  cdo_inq_record(streamID1, &varID, &levelID);

                  if (tsID == 0) recList[recID].set(varID, levelID);

                  if (tsID == 0 && varList1[varID].isConstant)
                    {
                      constFields[recID].init(varList1[varID]);
                      cdo_read_record(streamID1, constFields[recID]);
                    }
                  else
                    {
                      field1.init(varList1[varID]);
                      cdo_read_record(streamID1, field1);

                      hset.addVarLevelValues(varID, levelID, field1);
                    }
                }

              tsID++;
            }

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

        dtlist.stat_taxis_def_timestep(taxisID4, numSets);
        cdo_def_timestep(streamID4, otsID);

        for (int recID = 0; recID < maxrecs; ++recID)
          {
            auto [varID, levelID] = recList[recID].get();
            if (otsID && varList1[varID].isConstant) continue;

            cdo_def_record(streamID4, varID, levelID);

            if (varList1[varID].isConstant) { cdo_write_record(streamID4, constFields[recID]); }
            else
              {
                field1.init(varList1[varID]);
                hset.getVarLevelPercentiles(field1, varID, levelID, pn);
                cdo_write_record(streamID4, field1);
              }
          }

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

        for (int i = 0; i < nskip; ++i)
          {
            nrecs = cdo_stream_inq_timestep(streamID1, tsID);
            if (nrecs == 0) break;
            tsID++;
          }

        if (nrecs == 0) break;
      }
  }

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

    cdo_finish();
  }
};

void *
Timselpctl(void *process)
{
  ModuleTimselpctl timselpctl;
  timselpctl.init(process);
  timselpctl.run();
  timselpctl.close();

  return nullptr;
}
