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

      Intntime   intntime        Time interpolation
*/

#include <cdi.h>

#include "cdo_options.h"
#include "process_int.h"
#include "cdo_vlist.h"
#include "param_conversion.h"
#include "datetime.h"
#include "printinfo.h"

size_t inttime(double fac1, double fac2, size_t gridsize, const double *single1, const double *single2, Varray<double> &array,
               bool withMissval, double missval1, double missval2);

void *
Intntime(void *process)
{
  cdoInitialize(process);

  operatorInputArg("number of timesteps between 2 timesteps");
  if (operatorArgc() < 1) cdoAbort("Too few arguments!");

  const int numts = parameter2int(cdoOperatorArgv(0));
  if (numts < 2) cdoAbort("parameter must be greater than 1!");

  const auto streamID1 = cdoOpenRead(0);

  const auto vlistID1 = cdoStreamInqVlist(streamID1);
  const auto vlistID2 = vlistDuplicate(vlistID1);

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

  const auto nvars = vlistNvars(vlistID1);

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

  const auto gridsizemax = vlistGridsizeMax(vlistID1);
  Varray<double> array(gridsizemax);

  Varray3D<size_t> nmiss(2);
  nmiss[0].resize(nvars);
  nmiss[1].resize(nvars);
  Varray3D<double> vardata(2);
  vardata[0].resize(nvars);
  vardata[1].resize(nvars);

  for (int varID = 0; varID < nvars; varID++)
    {
      const auto gridsize = varList1[varID].gridsize;
      const auto nlevel = varList1[varID].nlevels;
      nmiss[0][varID].resize(nlevel);
      nmiss[1][varID].resize(nlevel);
      vardata[0][varID].resize(gridsize * nlevel);
      vardata[1][varID].resize(gridsize * nlevel);
    }

  const auto taxisID1 = vlistInqTaxis(vlistID1);
  const auto taxisID2 = taxisDuplicate(taxisID1);
  if (taxisHasBounds(taxisID2)) taxisDeleteBounds(taxisID2);
  vlistDefTaxis(vlistID2, taxisID2);

  const auto streamID2 = cdoOpenWrite(1);

  cdoDefVlist(streamID2, vlistID2);

  const auto calendar = taxisInqCalendar(taxisID1);

  int curFirst = 0, curSecond = 1;

  int tsID = 0;
  int tsIDo = 0;
  auto nrecs = cdoStreamInqTimestep(streamID1, tsID++);
  const auto vdate1 = taxisInqVdate(taxisID1);
  const auto vtime1 = taxisInqVtime(taxisID1);
  auto juldate1 = julianDateEncode(calendar, vdate1, vtime1);

  taxisCopyTimestep(taxisID2, taxisID1);
  cdoDefTimestep(streamID2, tsIDo++);
  for (int recID = 0; recID < nrecs; recID++)
    {
      int varID, levelID;
      cdoInqRecord(streamID1, &varID, &levelID);
      const auto offset = varList1[varID].gridsize * levelID;
      auto single1 = &vardata[curFirst][varID][offset];
      cdoReadRecord(streamID1, single1, &nmiss[curFirst][varID][levelID]);

      cdoDefRecord(streamID2, varID, levelID);
      cdoWriteRecord(streamID2, single1, nmiss[curFirst][varID][levelID]);
    }

  while ((nrecs = cdoStreamInqTimestep(streamID1, tsID++)))
    {
      const auto vdate2 = taxisInqVdate(taxisID1);
      const auto vtime2 = taxisInqVtime(taxisID1);
      const auto juldate2 = julianDateEncode(calendar, vdate2, vtime2);

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

          recList[recID].varID = varID;
          recList[recID].levelID = levelID;

          const auto offset = varList1[varID].gridsize * levelID;
          auto single2 = &vardata[curSecond][varID][offset];
          cdoReadRecord(streamID1, single2, &nmiss[curSecond][varID][levelID]);
        }

      for (int it = 1; it < numts; it++)
        {
          const double seconds = it * julianDateToSeconds(julianDateSub(juldate2, juldate1)) / numts;
          const auto juldate = julianDateAddSeconds(lround(seconds), juldate1);

          int64_t vdate;
          int vtime;
          julianDateDecode(calendar, juldate, vdate, vtime);

          if (Options::cdoVerbose) cdoPrint("%s %s", dateToString(vdate).c_str(), timeToString(vtime).c_str());

          taxisDefVdate(taxisID2, vdate);
          taxisDefVtime(taxisID2, vtime);
          cdoDefTimestep(streamID2, tsIDo++);

          const auto diff = julianDateToSeconds(julianDateSub(juldate2, juldate1));
          const auto fac1 = julianDateToSeconds(julianDateSub(juldate2, juldate)) / diff;
          const auto fac2 = julianDateToSeconds(julianDateSub(juldate, juldate1)) / diff;

          for (int recID = 0; recID < nrecs; recID++)
            {
              const auto varID = recList[recID].varID;
              const auto levelID = recList[recID].levelID;
              const auto gridsize = varList1[varID].gridsize;
              const auto offset = gridsize * levelID;
              const auto single1 = &vardata[curFirst][varID][offset];
              const auto single2 = &vardata[curSecond][varID][offset];

              const bool withMissval = nmiss[curFirst][varID][levelID] || nmiss[curSecond][varID][levelID];
              const auto nmiss3 = inttime(fac1, fac2, gridsize, single1, single2, array, withMissval, varList1[varID].missval,
                                          varList2[varID].missval);

              cdoDefRecord(streamID2, varID, levelID);
              cdoWriteRecord(streamID2, array.data(), nmiss3);
            }
        }

      taxisDefVdate(taxisID2, vdate2);
      taxisDefVtime(taxisID2, vtime2);
      cdoDefTimestep(streamID2, tsIDo++);
      for (int recID = 0; recID < nrecs; recID++)
        {
          const auto varID = recList[recID].varID;
          const auto levelID = recList[recID].levelID;
          const auto offset = varList2[varID].gridsize * levelID;
          auto single2 = &vardata[curSecond][varID][offset];

          cdoDefRecord(streamID2, varID, levelID);
          cdoWriteRecord(streamID2, single2, nmiss[curSecond][varID][levelID]);
        }

      juldate1 = juldate2;
      std::swap(curFirst, curSecond);
    }

  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  cdoFinish();

  return nullptr;
}
