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

  Copyright (C) 2003-2021 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 "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 = cdo_operator_argc();
  if (pargc)
    {
      auto pargv = cdo_get_oper_argv();

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

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

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

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

  cdo_operator_add("addtrend", FieldFunc_Add, 0, nullptr);
  cdo_operator_add("subtrend", FieldFunc_Sub, 0, nullptr);

  const auto operatorID = cdo_operator_id();
  const auto operfunc = cdo_operator_f1(operatorID);

  auto tstepIsEqual = true;
  trendarithGetParameter(tstepIsEqual);

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

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

  vlist_compare(vlistID1, vlistID2, CMP_DIM);
  vlist_compare(vlistID1, vlistID3, CMP_DIM);

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

  const auto streamID4 = cdo_open_write(3);
  cdo_def_vlist(streamID4, vlistID4);

  VarList varList;
  varListInit(varList, vlistID1);

  const auto gridsizemax = vlistGridsizeMax(vlistID1);

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

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

  {
    const auto nrecs = cdo_stream_inq_timestep(streamID2, 0);
    for (int recID = 0; recID < nrecs; recID++)
      {
        int varID, levelID;
        cdo_inq_record(streamID2, &varID, &levelID);
        cdo_read_record(streamID2, vars2[varID][levelID].vec_d.data(), &vars2[varID][levelID].nmiss);
      }
  }

  {
    const auto nrecs = cdo_stream_inq_timestep(streamID3, 0);
    for (int recID = 0; recID < nrecs; recID++)
      {
        int varID, levelID;
        cdo_inq_record(streamID3, &varID, &levelID);
        cdo_read_record(streamID3, vars3[varID][levelID].vec_d.data(), &vars3[varID][levelID].nmiss);
      }
  }

  const auto calendar = taxisInqCalendar(taxisID1);

  CheckTimeInc checkTimeInc;
  JulianDate juldate0;
  double deltat1 = 0.0;
  int tsID = 0;
  while (true)
    {
      const auto nrecs = cdo_stream_inq_timestep(streamID1, tsID);
      if (nrecs == 0) break;

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

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

      cdo_taxis_copy_timestep(taxisID4, taxisID1);
      cdo_def_timestep(streamID4, tsID);

      for (int recID = 0; recID < nrecs; recID++)
        {
          int varID, levelID;
          cdo_inq_record(streamID1, &varID, &levelID);
          cdo_read_record(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 == FieldFunc_Add)
            addtrend(zj, field1, vars2[varID][levelID], vars3[varID][levelID], field4);
          else
            subtrend(zj, field1, vars2[varID][levelID], vars3[varID][levelID], field4);

          cdo_def_record(streamID4, varID, levelID);
          cdo_write_record(streamID4, field4.vec_d.data(), field_num_miss(field4));
        }

      tsID++;
    }

  cdo_stream_close(streamID4);
  cdo_stream_close(streamID3);
  cdo_stream_close(streamID2);
  cdo_stream_close(streamID1);

  cdo_finish();

  return nullptr;
}
