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

      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 "functs.h"
#include "process_int.h"

constexpr int MaxMonths = 12;

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

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

static void
alreadyAllocated(bool isSeasonal, int mon, const char *seas_names[4])
{
  if (isSeasonal)
    cdoAbort("Season %s already allocated!", seas_names[mon]);
  else
    cdoAbort("%s already allocated! The second input file must contain monthly mean values for a maximum of one year.",
             mon_names[mon]);
}

static void
notFound(bool isSeasonal, int mon, const char *seas_names[4])
{
  if (isSeasonal)
    cdoAbort("Season %s not found!", seas_names[mon]);
  else
    cdoAbort("%s not found! The second input file must contain monthly mean values for a maximum of one year.", mon_names[mon]);
}

enum
{
  MONTHLY,
  SEASONAL
};

static void
addOperators(void)
{
  // clang-format off
  cdoOperatorAdd("ymonadd",  func_add, MONTHLY, nullptr);
  cdoOperatorAdd("ymonsub",  func_sub, MONTHLY, nullptr);
  cdoOperatorAdd("ymonmul",  func_mul, MONTHLY, nullptr);
  cdoOperatorAdd("ymondiv",  func_div, MONTHLY, nullptr);
  cdoOperatorAdd("yseasadd", func_add, SEASONAL, nullptr);
  cdoOperatorAdd("yseassub", func_sub, SEASONAL, nullptr);
  cdoOperatorAdd("yseasmul", func_mul, SEASONAL, nullptr);
  cdoOperatorAdd("yseasdiv", func_div, SEASONAL, nullptr);
  // clang-format on
}

void *
Ymonarith(void *process)
{
  int varID, levelID;
  const char *seas_names[4];

  cdoInitialize(process);

  addOperators();

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

  operatorCheckArgc(0);

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

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

  vlistCompare(vlistID1, vlistID2, CMP_ALL);

  VarList varList1;
  varListInit(varList1, vlistID1);

  const auto gridsizemax = vlistGridsizeMax(vlistID1);

  Field field;
  field.resize(gridsizemax);

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

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

  if (opertype == SEASONAL) getSeasonName(seas_names);

  FieldVector2D vars2[MaxMonths];

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

      auto mon = getMonthIndex(taxisInqVdate(taxisID2));
      if (opertype == SEASONAL) mon = monthToSeason(mon + 1);
      if (vars2[mon].size()) alreadyAllocated(opertype == SEASONAL, mon, seas_names);

      fieldsFromVlist(vlistID2, vars2[mon], FIELD_VEC);

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

      tsID++;
    }

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

      auto mon = getMonthIndex(taxisInqVdate(taxisID1));
      if (opertype == SEASONAL) mon = monthToSeason(mon + 1);
      if (vars2[mon].size() == 0) notFound(opertype == SEASONAL, mon, seas_names);

      taxisCopyTimestep(taxisID3, taxisID1);
      cdoDefTimestep(streamID3, tsID);

      for (int recID = 0; recID < nrecs; recID++)
        {
          cdoInqRecord(streamID1, &varID, &levelID);
          cdoReadRecord(streamID1, field.vec_d.data(), &field.nmiss);
          field.size = varList1[varID].gridsize;
          field.grid = varList1[varID].gridID;
          field.missval = varList1[varID].missval;

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

          cdoDefRecord(streamID3, varID, levelID);
          cdoWriteRecord(streamID3, field.vec_d.data(), field.nmiss);
        }

      tsID++;
    }

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

  cdoFinish();

  return nullptr;
}
