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

      Selyearidx    selyearidx         Select index of year
*/

#include <cdi.h>

#include "functs.h"
#include "process_int.h"
#include "cdo_vlist.h"

void *
Selyearidx(void *process)
{
  int varID, levelID;
  int year, month, day;
  size_t nmiss;

  cdoInitialize(process);

  cdoOperatorAdd("selyearidx", 0, 0, nullptr);
  cdoOperatorAdd("seltimeidx", 1, 0, nullptr);

  const bool ltime = cdoOperatorF1(cdoOperatorID());

  const auto streamID1 = cdoOpenRead(0);
  const int vlistID1 = cdoStreamInqVlist(streamID1);

  const int taxisID1 = vlistInqTaxis(vlistID1);

  const auto streamID2 = cdoOpenRead(1);
  const auto vlistID2 = cdoStreamInqVlist(streamID2);
  const auto taxisID2 = vlistInqTaxis(vlistID2);

  vlistCompare(vlistID1, vlistID2, CMP_ALL);

  const auto vlistID3 = vlistDuplicate(vlistID2);
  const auto taxisID3 = taxisDuplicate(taxisID1);
  vlistDefTaxis(vlistID3, taxisID3);

  const auto streamID3 = cdoOpenWrite(2);
  cdoDefVlist(streamID3, vlistID3);

  VarList varList1, varList2;
  varListInit(varList1, vlistID1);
  varListInit(varList2, vlistID2);

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

  const auto gridsizemax = vlistGridsizeMax(vlistID1);

  Varray<double> array(gridsizemax);

  FieldVector2D vars1, vars2;
  fieldsFromVlist(vlistID1, vars1, FIELD_VEC);
  fieldsFromVlist(vlistID2, vars2, FIELD_VEC);

  const int nvars = vlistNvars(vlistID1);
  for (varID = 0; varID < nvars; ++varID)
    {
      const auto gridsize = varList1[varID].gridsize;
      const auto nlevels = varList1[varID].nlevels;
      const auto missval = varList2[varID].missval;
      for (levelID = 0; levelID < nlevels; ++levelID)
        {
          for (size_t i = 0; i < gridsize; ++i) vars2[varID][levelID].vec_d[i] = missval;
        }
    }

  int tsID = 0;
  int tsID2 = 0;
  int tsID3 = 0;
  while (true)
    {
      auto nrecs = cdoStreamInqTimestep(streamID1, tsID);
      if (nrecs == 0) break;

      auto vdate = taxisInqVdate(taxisID1);
      cdiDecodeDate(vdate, &year, &month, &day);
      int year1 = year;

      const bool lexactdate = gridsizemax == 1 && nrecs == 1;

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

          if (tsID == 0)
            {
              recList[recID].varID = varID;
              recList[recID].levelID = levelID;
              recList[recID].lconst = varList1[varID].timetype == TIME_CONSTANT;
            }
        }

      int nrecs2;
      int nsets = 0;
      while ((nrecs2 = cdoStreamInqTimestep(streamID2, tsID2)))
        {
          vdate = taxisInqVdate(taxisID2);
          cdiDecodeDate(vdate, &year, &month, &day);

          if (ltime == false && year1 != year) break;

          for (int recID = 0; recID < nrecs2; recID++)
            {
              cdoInqRecord(streamID2, &varID, &levelID);
              cdoReadRecord(streamID2, array.data(), &nmiss);

              const size_t gridsize = varList2[varID].gridsize;
              for (size_t i = 0; i < gridsize; ++i)
                if (nsets == (int) std::lround(vars1[varID][levelID].vec_d[i]))
                  {
                    if (lexactdate) taxisCopyTimestep(taxisID3, taxisID2);
                    vars2[varID][levelID].vec_d[i] = array[i];
                  }
            }

          nsets++;
          tsID2++;
        }

      if (nsets)
        {
          if (!lexactdate) taxisCopyTimestep(taxisID3, taxisID1);
          cdoDefTimestep(streamID3, tsID3);

          for (int recID = 0; recID < maxrecs; recID++)
            {
              if (tsID && recList[recID].lconst) continue;

              varID = recList[recID].varID;
              levelID = recList[recID].levelID;
              cdoDefRecord(streamID3, varID, levelID);
              cdoWriteRecord(streamID3, vars2[varID][levelID].vec_d.data(), fieldNumMiss(vars2[varID][levelID]));
            }

          tsID3++;
        }

      if (nsets == 0)
        {
          cdoWarning("First input stream has more timesteps than the second input stream!");
          break;
        }

      if (nrecs2 == 0) break;

      tsID++;
    }

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

  cdoFinish();

  return nullptr;
}
