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

      Set        setcode         Set code number
      Set        setparam        Set parameter identifier
      Set        setname         Set variable name
      Set        setlevel        Set level
      Set        setltype        Set GRIB level type
*/

#include <cdi.h>

#include "cdo_options.h"
#include "process_int.h"
#include "param_conversion.h"
#include "cdo_zaxis.h"

static void
setlevel(int vlistID2, double newlevel)
{
  const auto nzaxis = vlistNzaxis(vlistID2);
  for (int index = 0; index < nzaxis; index++)
    {
      const auto zaxisID1 = vlistZaxis(vlistID2, index);
      const auto zaxisID2 = zaxisDuplicate(zaxisID1);
      const auto nlevs = zaxisInqSize(zaxisID2);
      Varray<double> levels(nlevs);
      cdoZaxisInqLevels(zaxisID2, levels.data());
      levels[0] = newlevel;
      zaxisDefLevels(zaxisID2, levels.data());
      vlistChangeZaxis(vlistID2, zaxisID1, zaxisID2);
    }
}

static void
setltype(int vlistID2, double newval)
{
  const auto nzaxis = vlistNzaxis(vlistID2);
  for (int index = 0; index < nzaxis; index++)
    {
      const auto zaxisID1 = vlistZaxis(vlistID2, index);
      const auto zaxisID2 = zaxisDuplicate(zaxisID1);
      const auto zaxistype = ZAXIS_GENERIC;
      zaxisChangeType(zaxisID2, zaxistype);
      cdiDefKeyInt(zaxisID2, CDI_GLOBAL, CDI_KEY_TYPEOFFIRSTFIXEDSURFACE, newval);
      vlistChangeZaxis(vlistID2, zaxisID1, zaxisID2);
    }
}

void *
Set(void *process)
{
  int nrecs, newval = -1, tabnum = 0;
  int varID, levelID;
  size_t nmiss;
  int newparam = 0;
  const char *newname = nullptr, *newunit = nullptr;
  double newlevel = 0;

  cdoInitialize(process);

  // clang-format off
  const auto SETCODE    = cdoOperatorAdd("setcode",    0, 0, "code number");
  const auto SETPARAM   = cdoOperatorAdd("setparam",   0, 0, "parameter identifier (format: code[.tabnum] or num[.cat[.dis]])");
  const auto SETNAME    = cdoOperatorAdd("setname",    0, 0, "variable name");
  const auto SETUNIT    = cdoOperatorAdd("setunit",    0, 0, "variable unit");
  const auto SETLEVEL   = cdoOperatorAdd("setlevel",   0, 0, "level");
  const auto SETLTYPE   = cdoOperatorAdd("setltype",   0, 0, "GRIB level type");
  const auto SETTABNUM  = cdoOperatorAdd("settabnum",  0, 0, "GRIB table number");
  // clang-format on

  const auto operatorID = cdoOperatorID();

  operatorInputArg(cdoOperatorEnter(operatorID));
  if (operatorID == SETCODE || operatorID == SETLTYPE)
    {
      newval = parameter2int(cdoOperatorArgv(0));
    }
  else if (operatorID == SETPARAM)
    {
      newparam = stringToParam(cdoOperatorArgv(0));
    }
  else if (operatorID == SETNAME)
    {
      newname = cdoOperatorArgv(0).c_str();
    }
  else if (operatorID == SETUNIT)
    {
      newunit = cdoOperatorArgv(0).c_str();
    }
  else if (operatorID == SETTABNUM)
    {
      tabnum = parameter2int(cdoOperatorArgv(0));
    }
  else if (operatorID == SETLEVEL)
    {
      newlevel = parameter2double(cdoOperatorArgv(0));
    }

  const auto streamID1 = cdoOpenRead(0);

  const auto vlistID1 = cdoStreamInqVlist(streamID1);
  const auto vlistID2 = vlistDuplicate(vlistID1);
  /* vlistPrint(vlistID2);*/

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

  if (operatorID == SETCODE)
    {
      const auto nvars = vlistNvars(vlistID2);
      for (varID = 0; varID < nvars; varID++) vlistDefVarCode(vlistID2, varID, newval);
    }
  else if (operatorID == SETPARAM)
    {
      vlistDefVarParam(vlistID2, 0, newparam);
    }
  else if (operatorID == SETNAME)
    {
      cdiDefKeyString(vlistID2, 0, CDI_KEY_NAME, newname);
    }
  else if (operatorID == SETUNIT)
    {
      cdiDefKeyString(vlistID2, 0, CDI_KEY_UNITS, newunit);
    }
  else if (operatorID == SETTABNUM)
    {
      const auto tableID = tableDef(-1, tabnum, nullptr);
      const auto nvars = vlistNvars(vlistID2);
      for (varID = 0; varID < nvars; varID++) vlistDefVarTable(vlistID2, varID, tableID);
    }
  else if (operatorID == SETLEVEL)
    {
      setlevel(vlistID2, newlevel);
    }
  else if (operatorID == SETLTYPE)
    {
      setltype(vlistID2, newval);
    }

  // vlistPrint(vlistID2);
  const auto streamID2 = cdoOpenWrite(1);
  cdoDefVlist(streamID2, vlistID2);

  auto gridsizemax = vlistGridsizeMax(vlistID1);
  if (vlistNumber(vlistID1) != CDI_REAL) gridsizemax *= 2;
  Varray<double> array(gridsizemax);

  int tsID1 = 0;
  while ((nrecs = cdoStreamInqTimestep(streamID1, tsID1)))
    {
      taxisCopyTimestep(taxisID2, taxisID1);
      cdoDefTimestep(streamID2, tsID1);

      for (int recID = 0; recID < nrecs; recID++)
        {
          cdoInqRecord(streamID1, &varID, &levelID);
          cdoDefRecord(streamID2, varID, levelID);

          cdoReadRecord(streamID1, array.data(), &nmiss);
          cdoWriteRecord(streamID2, array.data(), nmiss);
        }

      tsID1++;
    }

  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  cdoFinish();

  return nullptr;
}
