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

  Copyright (C) 2006 Brockmann Consult
  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:

      Timselpctl    timselpctl         Time range percentiles
*/

#include <cdi.h>

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

void *
Timselpctl(void *process)
{
  TimeStat timestat_date = TimeStat::MEAN;
  int nrecs = 0;
  int tsID;
  size_t nmiss;

  cdoInitialize(process);

  cdoOperatorAdd("timselpctl", func_pctl, 0, nullptr);

  operatorInputArg("percentile number, nsets <,noffset <,nskip>>");

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

  const auto pn = parameter2double(cdoOperatorArgv(0));
  const auto ndates = parameter2int(cdoOperatorArgv(1));
  int noffset = 0, nskip = 0;
  if (nargc > 2) noffset = parameter2int(cdoOperatorArgv(2));
  if (nargc > 3) nskip = parameter2int(cdoOperatorArgv(3));

  if (Options::cdoVerbose) cdoPrint("nsets = %d, noffset = %d, nskip = %d", ndates, noffset, nskip);

  const auto streamID1 = cdoOpenRead(0);
  const auto streamID2 = cdoOpenRead(1);
  const auto streamID3 = cdoOpenRead(2);

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

  vlistCompare(vlistID1, vlistID2, CMP_ALL);
  vlistCompare(vlistID1, vlistID3, CMP_ALL);

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

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

  const auto streamID4 = cdoOpenWrite(3);
  cdoDefVlist(streamID4, vlistID4);

  const auto nvars = vlistNvars(vlistID1);

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

  DateTimeList dtlist;
  dtlist.setStat(timestat_date);
  dtlist.setCalendar(taxisInqCalendar(taxisID1));

  const auto gridsizemax = vlistGridsizeMax(vlistID1);

  Field field;
  field.resize(gridsizemax);

  FieldVector2D vars1;
  fieldsFromVlist(vlistID1, vars1, FIELD_VEC);
  HistogramSet hset(nvars);

  VarList varList1;
  varListInit(varList1, vlistID1);

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

  for (tsID = 0; tsID < noffset; tsID++)
    {
      nrecs = cdoStreamInqTimestep(streamID1, tsID);
      if (nrecs == 0) break;

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

  int otsID = 0;
  if (tsID < noffset)
    {
      cdoWarning("noffset is larger than number of timesteps!");
      goto LABEL_END;
    }

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

      const auto vdate2 = taxisInqVdate(taxisID2);
      const auto vtime2 = taxisInqVtime(taxisID2);
      const auto vdate3 = taxisInqVdate(taxisID3);
      const auto vtime3 = taxisInqVtime(taxisID3);
      if (vdate2 != vdate3 || vtime2 != vtime3)
        cdoAbort("Verification dates at time step %d of %s and %s differ!", otsID + 1, cdoGetStreamName(1), cdoGetStreamName(2));

      for (int recID = 0; recID < nrecs; recID++)
        {
          int varID, levelID;
          cdoInqRecord(streamID2, &varID, &levelID);
          cdoReadRecord(streamID2, vars1[varID][levelID].vec_d.data(), &nmiss);
          vars1[varID][levelID].nmiss = nmiss;
        }

      for (int recID = 0; recID < nrecs; recID++)
        {
          int varID, levelID;
          cdoInqRecord(streamID3, &varID, &levelID);
          cdoReadRecord(streamID3, field.vec_d.data(), &field.nmiss);
          field.size = varList1[varID].gridsize;
          field.grid = varList1[varID].gridID;
          field.missval = varList1[varID].missval;

          hset.defVarLevelBounds(varID, levelID, vars1[varID][levelID], field);
        }

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

            dtlist.taxisInqTimestep(taxisID1, nsets);

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

                cdoReadRecord(streamID1, vars1[varID][levelID].vec_d.data(), &nmiss);
                vars1[varID][levelID].nmiss = nmiss;

                hset.addSubVarLevelValues(varID, levelID, vars1[varID][levelID], 1, FIELD_VEC);
              }

            tsID++;
          }

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

      for (int varID = 0; varID < nvars; varID++)
        {
          if (varList1[varID].timetype == TIME_CONSTANT) continue;

          const auto nlevels = varList1[varID].nlevels;
          for (int levelID = 0; levelID < nlevels; levelID++) hset.getVarLevelPercentiles(vars1[varID][levelID], varID, levelID, pn, FIELD_VEC);
        }

      dtlist.statTaxisDefTimestep(taxisID4, nsets);
      cdoDefTimestep(streamID4, 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;
          cdoDefRecord(streamID4, varID, levelID);
          cdoWriteRecord(streamID4, vars1[varID][levelID].vec_d.data(), vars1[varID][levelID].nmiss);
        }

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

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

      if (nrecs == 0) break;
    }

LABEL_END:

  cdoStreamClose(streamID4);
  cdoStreamClose(streamID3);
  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  cdoFinish();

  return nullptr;
}
