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

     Subtrend   subtrend        Subtract trend
*/

#include <cdi.h>

#include "functs.h"
#include "process_int.h"
#include "cdo_vlist.h"
#include "datetime.h"
#include "pmlist.h"
#include "param_conversion.h"

static void
addtrend(double zj, const Field &field1, const Field &field2, const Field &field3, Field &field4)
{
  const auto gridsize = field1.size;
  const auto missval = field1.missval;
  const auto missval1 = missval;
  const auto missval2 = missval;
  for (size_t i = 0; i < gridsize; i++) field4.vec_d[i] = ADDMN(field1.vec_d[i], ADDMN(field2.vec_d[i], MULMN(field3.vec_d[i], zj)));
}

static void
subtrend(double zj, const Field &field1, const Field &field2, const Field &field3, Field &field4)
{
  const auto gridsize = field1.size;
  const auto missval = field1.missval;
  const auto missval1 = missval;
  const auto missval2 = missval;
  for (size_t i = 0; i < gridsize; i++) field4.vec_d[i] = SUBMN(field1.vec_d[i], ADDMN(field2.vec_d[i], MULMN(field3.vec_d[i], zj)));
}

static void
trendarithGetParameter(bool &tstepIsEqual)
{
  const auto pargc = cdoOperatorArgc();
  if (pargc)
    {
      auto pargv = cdoGetOperArgv();

      KVList kvlist;
      kvlist.name = "TREND";
      if (kvlist.parseArguments(pargc, pargv) != 0) cdoAbort("Parse error!");
      if (Options::cdoVerbose) kvlist.print();

      for (const auto &kv : kvlist)
        {
          const auto &key = kv.key;
          if (kv.nvalues > 1) cdoAbort("Too many values for parameter key >%s<!", key.c_str());
          if (kv.nvalues < 1) cdoAbort("Missing value for parameter key >%s<!", key.c_str());
          const auto &value = kv.values[0];

          // clang-format off
          if      (key == "equal")  tstepIsEqual = parameter2bool(value);
          else cdoAbort("Invalid parameter key >%s<!", key.c_str());
          // clang-format on
        }
    }
}

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

  cdoOperatorAdd("addtrend",     func_add,     0, nullptr);
  cdoOperatorAdd("subtrend",     func_sub,     0, nullptr);

  const auto operatorID = cdoOperatorID();
  const auto operfunc = cdoOperatorF1(operatorID);

  auto tstepIsEqual = true;
  trendarithGetParameter(tstepIsEqual);

  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_DIM);
  vlistCompare(vlistID1, vlistID3, CMP_DIM);

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

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

  VarList varList;
  varListInit(varList, vlistID1);

  const auto gridsizemax = vlistGridsizeMax(vlistID1);

  Field field1, field4;
  field1.resize(gridsizemax);
  field4.resize(gridsizemax);

  FieldVector2D vars2, vars3;
  fieldsFromVlist(vlistID1, vars2, FIELD_VEC);
  fieldsFromVlist(vlistID1, vars3, FIELD_VEC);

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

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

  const auto calendar = taxisInqCalendar(taxisID1);

  CheckTimeInc checkTimeInc;
  JulianDate juldate0;
  double deltat1 = 0.0;
  tsID = 0;
  while ((nrecs = cdoStreamInqTimestep(streamID1, tsID)))
    {
      const auto vdate = taxisInqVdate(taxisID1);
      const auto vtime = taxisInqVtime(taxisID1);

      if (tstepIsEqual) checkTimeIncrement(tsID, calendar, vdate, vtime, checkTimeInc);
      const auto zj = tstepIsEqual ? (double) tsID : deltaTimeStep0(tsID, calendar, vdate, vtime, juldate0, deltat1);

      taxisCopyTimestep(taxisID4, taxisID1);
      cdoDefTimestep(streamID4, tsID);

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

          field1.size = varList[varID].gridsize;
          field1.missval = varList[varID].missval;
          field4.size = varList[varID].gridsize;
          field4.missval = varList[varID].missval;

          if (operfunc == func_add)
            addtrend(zj, field1, vars2[varID][levelID], vars3[varID][levelID], field4);
          else
            subtrend(zj, field1, vars2[varID][levelID], vars3[varID][levelID], field4);

          cdoDefRecord(streamID4, varID, levelID);
          cdoWriteRecord(streamID4, field4.vec_d.data(), fieldNumMiss(field4));
        }

      tsID++;
    }

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

  cdoFinish();

  return nullptr;
}
