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

      Yhourarith  yhouradd         Add multi-year hourly time series
      Yhourarith  yhoursub         Subtract multi-year hourly time series
      Yhourarith  yhourmul         Multiply multi-year hourly time series
      Yhourarith  yhourdiv         Divide multi-year hourly time series
*/

#include <cdi.h>

#include "cdo_vlist.h"
#include "datetime.h"
#include "functs.h"
#include "process_int.h"
#include "printinfo.h"

constexpr int MaxHours = 9301;  // 31*12*25 + 1

static int
getHourOfYearIndex(int64_t vdate, int vtime)
{
  const auto houroy = decodeHourOfYear(vdate, vtime);

  if (houroy < 0 || houroy >= MaxHours)
    cdoAbort("Hour of year %d out of range (%s %s)!", houroy, dateToString(vdate).c_str(), timeToString(vtime).c_str());

  return houroy;
}

void *
Yhourarith(void *process)
{
  int nrecs;
  int varID, levelID;

  cdoInitialize(process);

  cdoOperatorAdd("yhouradd", func_add, 0, nullptr);
  cdoOperatorAdd("yhoursub", func_sub, 0, nullptr);
  cdoOperatorAdd("yhourmul", func_mul, 0, nullptr);
  cdoOperatorAdd("yhourdiv", func_div, 0, nullptr);

  const auto operatorID = cdoOperatorID();
  const auto operfunc = cdoOperatorF1(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);

  FieldVector2D vars2[MaxHours];

  int tsID = 0;
  while ((nrecs = cdoStreamInqTimestep(streamID2, tsID)))
    {
      const auto houroy = getHourOfYearIndex(taxisInqVdate(taxisID2), taxisInqVtime(taxisID2));
      if (vars2[houroy].size() > 0) cdoAbort("Hour of year index %d already allocated!", houroy);

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

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

      tsID++;
    }

  tsID = 0;
  while ((nrecs = cdoStreamInqTimestep(streamID1, tsID)))
    {
      const auto houroy = getHourOfYearIndex(taxisInqVdate(taxisID1), taxisInqVtime(taxisID1));
      if (vars2[houroy].size() == 0) cdoAbort("Hour of year index %d not found!", houroy);

      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.grid = varList1[varID].gridID;
          field.missval = varList1[varID].missval;

          vfarfun(field, vars2[houroy][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;
}
