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

      Yseaspctl  yseaspctl       Multi-year seasonal percentiles
*/

#include <cdi.h>

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

void *
Yseaspctl(void *process)
{
  constexpr int MaxSeasons = 4;
  int nrecs;
  size_t nmiss;
  long nsets[MaxSeasons] = { 0 };
  CdoDateTime datetime1[MaxSeasons], datetime2[MaxSeasons];
  FieldVector2D vars1[MaxSeasons];
  HistogramSet hsets[MaxSeasons];

  cdoInitialize(process);
  cdoOperatorAdd("yseaspctl", func_pctl, 0, nullptr);

  operatorInputArg("percentile number");
  const auto pn = parameter2double(cdoOperatorArgv(0));

  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);

  VarList varList1;
  varListInit(varList1, vlistID1);

  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);
  if (taxisHasBounds(taxisID4)) taxisDeleteBounds(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);

  const auto gridsizemax = vlistGridsizeMax(vlistID1);

  Field field;
  field.resize(gridsizemax);

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

      const auto vdate = taxisInqVdate(taxisID2);
      const auto vtime = taxisInqVtime(taxisID2);

      if (vdate != taxisInqVdate(taxisID3))
        cdoAbort("Verification dates at time step %d of %s and %s differ!", tsID + 1, cdoGetStreamName(1), cdoGetStreamName(2));

      if (Options::cdoVerbose) cdoPrint("process timestep: %d %d %d", tsID + 1, vdate, vtime);

      const auto seas = monthToSeason(decodeMonth(vdate));

      setDateTime(datetime2[seas], vdate, vtime);

      if (!vars1[seas].size())
        {
          fieldsFromVlist(vlistID1, vars1[seas], FIELD_VEC);

          hsets[seas].create(nvars);

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

      for (int recID = 0; recID < nrecs; recID++)
        {
          int varID, levelID;
          cdoInqRecord(streamID2, &varID, &levelID);
          cdoReadRecord(streamID2, vars1[seas][varID][levelID].vec_d.data(), &nmiss);
          vars1[seas][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.grid = vars1[seas][varID][levelID].grid;
          field.missval = vars1[seas][varID][levelID].missval;

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

      tsID++;
    }

  tsID = 0;
  while ((nrecs = cdoStreamInqTimestep(streamID1, tsID)))
    {
      const auto vdate = taxisInqVdate(taxisID1);
      const auto vtime = taxisInqVtime(taxisID1);

      const auto month = decodeMonth(vdate);
      if (month < 0 || month > 16) cdoAbort("Month %d out of range!", month);

      const auto seas = monthToSeason(month);

      setDateTime(datetime1[seas], vdate, vtime);

      if (!vars1[seas].size()) cdoAbort("No data for season %d in %s and %s", seas, cdoGetStreamName(1), cdoGetStreamName(2));

      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;
            }

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

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

      nsets[seas]++;
      tsID++;
    }

  int otsID = 0;
  for (int seas = 0; seas < MaxSeasons; seas++)
    if (nsets[seas])
      {
        if (decodeMonthAndDay(datetime1[seas].date) != decodeMonthAndDay(datetime2[seas].date))
          cdoAbort("Verification dates for the season %d of %s and %s are different!", seas, cdoGetStreamName(0),
                   cdoGetStreamName(1));

        for (int varID = 0; varID < nvars; varID++)
          {
            if (vlistInqVarTimetype(vlistID1, varID) == TIME_CONSTANT) continue;

            const auto nlevels = zaxisInqSize(vlistInqVarZaxis(vlistID1, varID));
            for (int levelID = 0; levelID < nlevels; levelID++)
              hsets[seas].getVarLevelPercentiles(vars1[seas][varID][levelID], varID, levelID, pn, FIELD_VEC);
          }

        taxisDefVdate(taxisID4, datetime1[seas].date);
        taxisDefVtime(taxisID4, datetime1[seas].time);
        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[seas][varID][levelID].vec_d.data(), vars1[seas][varID][levelID].nmiss);
          }

        otsID++;
      }

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

  cdoFinish();

  return nullptr;
}
