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

  Author: Uwe Schulzweida

*/

/*
   This module contains the following operators:

      Ymonarith  ymonadd         Add multi-year monthly time series
      Ymonarith  ymonsub         Subtract multi-year monthly time series
      Ymonarith  ymonmul         Multiply multi-year monthly time series
      Ymonarith  ymondiv         Divide multi-year monthly time series
      Ymonarith  yseasadd        Add multi-year seasonal time series
      Ymonarith  yseassub        Subtract multi-year seasonal time series
      Ymonarith  yseasmul        Multiply multi-year seasonal time series
      Ymonarith  yseasdiv        Divide multi-year seasonal time series
*/

#include <cdi.h>

#include "cdo_vlist.h"
#include "cdo_season.h"
#include "process_int.h"

constexpr int MaxMonths = 12;

static const char **seasonNames = nullptr;
static const char *monthNames[]
    = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };

static int
get_month_index(const int64_t vdate)
{
  int year, mon, day;
  cdiDecodeDate(vdate, &year, &mon, &day);
  if (mon < 1 || mon > MaxMonths) cdo_abort("Month %d out of range!", mon);
  mon--;
  return mon;
}

static void
already_allocated(bool isSeasonal, int mon)
{
  if (isSeasonal)
    cdo_abort("Season %s already allocated!", seasonNames[mon]);
  else
    cdo_abort("%s already allocated! The second input file must contain monthly mean values for a maximum of one year.",
              monthNames[mon]);
}

static void
not_found(bool isSeasonal, int mon)
{
  if (isSeasonal)
    cdo_abort("Season %s not found!", seasonNames[mon]);
  else
    cdo_abort("%s not found! The second input file must contain monthly mean values for a maximum of one year.", monthNames[mon]);
}

enum
{
  MONTHLY,
  SEASONAL
};

static void
add_operators(void)
{
  // clang-format off
  cdo_operator_add("ymonadd",  FieldFunc_Add, MONTHLY, nullptr);
  cdo_operator_add("ymonsub",  FieldFunc_Sub, MONTHLY, nullptr);
  cdo_operator_add("ymonmul",  FieldFunc_Mul, MONTHLY, nullptr);
  cdo_operator_add("ymondiv",  FieldFunc_Div, MONTHLY, nullptr);
  cdo_operator_add("yseasadd", FieldFunc_Add, SEASONAL, nullptr);
  cdo_operator_add("yseassub", FieldFunc_Sub, SEASONAL, nullptr);
  cdo_operator_add("yseasmul", FieldFunc_Mul, SEASONAL, nullptr);
  cdo_operator_add("yseasdiv", FieldFunc_Div, SEASONAL, nullptr);
  // clang-format on
}

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

  add_operators();

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

  const auto isSeasonal = (opertype == SEASONAL);

  operator_check_argc(0);

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

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

  vlist_compare(vlistID1, vlistID2, CMP_ALL);

  VarList varList1;
  varListInit(varList1, vlistID1);

  Field field;

  const auto taxisID1 = vlistInqTaxis(vlistID1);
  const auto taxisID2 = vlistInqTaxis(vlistID2);
  const auto taxisID3 = taxisDuplicate(taxisID1);
  vlistDefTaxis(vlistID3, taxisID3);

  const auto streamID3 = cdo_open_write(2);
  cdo_def_vlist(streamID3, vlistID3);

  if (isSeasonal) seasonNames = get_season_name();

  FieldVector2D vars2[MaxMonths];

  int tsID = 0;
  while (true)
    {
      const auto nrecs = cdo_stream_inq_timestep(streamID2, tsID);
      if (nrecs == 0) break;

      auto mon = get_month_index(taxisInqVdate(taxisID2));
      if (isSeasonal) mon = month_to_season(mon + 1);
      if (vars2[mon].size()) already_allocated(isSeasonal, mon);

      fields_from_vlist(vlistID2, vars2[mon], FIELD_VEC | FIELD_NAT);

      for (int recID = 0; recID < nrecs; recID++)
        {
          int varID, levelID;
          cdo_inq_record(streamID2, &varID, &levelID);
          cdo_read_record(streamID2, vars2[mon][varID][levelID]);
        }

      tsID++;
    }

  cdo_stream_close(streamID2);

  tsID = 0;
  while (true)
    {
      const auto nrecs = cdo_stream_inq_timestep(streamID1, tsID);
      if (nrecs == 0) break;

      auto mon = get_month_index(taxisInqVdate(taxisID1));
      if (isSeasonal) mon = month_to_season(mon + 1);
      if (vars2[mon].size() == 0) not_found(isSeasonal, mon);

      cdo_taxis_copy_timestep(taxisID3, taxisID1);
      cdo_def_timestep(streamID3, tsID);

      for (int recID = 0; recID < nrecs; recID++)
        {
          int varID, levelID;
          cdo_inq_record(streamID1, &varID, &levelID);
          field.init(varList1[varID]);
          cdo_read_record(streamID1, field);

          field2_function(field, vars2[mon][varID][levelID], operfunc);

          cdo_def_record(streamID3, varID, levelID);
          cdo_write_record(streamID3, field);
        }

      tsID++;
    }

  cdo_stream_close(streamID3);
  cdo_stream_close(streamID1);

  cdo_finish();

  return nullptr;
}
