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

#include <cdi.h>

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

static void
isosurface(double isoval, long nlev1, const Varray<double> &lev1, const FieldVector &field3D, Field &field2D)
{
  const auto gridsize = gridInqSize(field3D[0].grid);
  const auto nmiss = field3D[0].nmiss;
  const auto missval = field3D[0].missval;
  auto &data2D = field2D.vec_d;

  for (size_t i = 0; i < gridsize; ++i)
    {
      data2D[i] = missval;

      for (long k = 0; k < (nlev1 - 1); ++k)
        {
          const auto val1 = field3D[k].vec_d[i];
          const auto val2 = field3D[k + 1].vec_d[i];

          if (nmiss)
            {
              const bool lmiss1 = DBL_IS_EQUAL(val1, missval);
              const bool lmiss2 = DBL_IS_EQUAL(val2, missval);
              if (lmiss1 && lmiss2) continue;
              if (lmiss1 && IS_EQUAL(isoval, val2)) data2D[i] = lev1[k + 1];
              if (lmiss2 && IS_EQUAL(isoval, val1)) data2D[i] = lev1[k];
              if (lmiss1 || lmiss2) continue;
            }

          if ((isoval >= val1 && isoval <= val2) || (isoval >= val2 && isoval <= val1))
            {
              data2D[i] = IS_EQUAL(val1, val2) ? lev1[k] : intlin(isoval, lev1[k], val1, lev1[k + 1], val2);
              break;
            }
        }
    }

  field2D.missval = missval;
  field2D.nmiss = varrayNumMV(gridsize, data2D, missval);
}

void *
Isosurface(void *process)
{
  int nrecs;
  int zaxisID1 = -1;
  size_t nmiss;

  cdoInitialize(process);

  operatorInputArg("isoval");

  operatorCheckArgc(1);

  const auto isoval = parameter2double(cdoOperatorArgv(0));

  if (Options::cdoVerbose) cdoPrint("Isoval: %g", isoval);

  const auto streamID1 = cdoOpenRead(0);

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

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

  const auto nzaxis = vlistNzaxis(vlistID1);
  int nlevels = 0;
  int i;
  for (i = 0; i < nzaxis; i++)
    {
      const auto zaxisID = vlistZaxis(vlistID1, i);
      nlevels = zaxisInqSize(zaxisID);
      if (zaxisInqType(zaxisID) != ZAXIS_HYBRID && zaxisInqType(zaxisID) != ZAXIS_HYBRID_HALF)
        if (nlevels > 1)
          {
            zaxisID1 = zaxisID;
            break;
          }
    }
  if (i == nzaxis) cdoAbort("No processable variable found!");

  const auto nlev1 = nlevels;
  Varray<double> lev1(nlev1);
  cdoZaxisInqLevels(zaxisID1, &lev1[0]);

  const int zaxisIDsfc = zaxisFromName("surface");
  for (i = 0; i < nzaxis; i++)
    if (zaxisID1 == vlistZaxis(vlistID1, i)) vlistChangeZaxisIndex(vlistID2, i, zaxisIDsfc);

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

  VarList varList1, varList2;
  varListInit(varList1, vlistID1);
  varListInit(varList2, vlistID2);

  const auto gridsizemax = vlistGridsizeMax(vlistID1);

  Field field;
  field.resize(gridsizemax);

  const auto nvars = vlistNvars(vlistID1);

  std::vector<bool> liso(nvars), vars(nvars);
  FieldVector2D vars1;
  fieldsFromVlist(vlistID1, vars1, FIELD_VEC);

  for (int varID = 0; varID < nvars; varID++) liso[varID] = (varList1[varID].zaxisID == zaxisID1);

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

      for (int varID = 0; varID < nvars; varID++) vars[varID] = false;

      for (int recID = 0; recID < nrecs; recID++)
        {
          int varID, levelID;
          cdoInqRecord(streamID1, &varID, &levelID);
          cdoReadRecord(streamID1, vars1[varID][levelID].vec_d.data(), &nmiss);
          vars1[varID][0].nmiss += nmiss;
          vars[varID] = true;
        }

      for (int varID = 0; varID < nvars; varID++)
        {
          if (vars[varID])
            {
              if (liso[varID])
                {
                  isosurface(isoval, nlev1, lev1, vars1[varID], field);

                  cdoDefRecord(streamID2, varID, 0);
                  cdoWriteRecord(streamID2, field.vec_d.data(), field.nmiss);
                }
              else
                {
                  for (int levelID = 0; levelID < varList2[varID].nlevels; levelID++)
                    {
                      auto &single = vars1[varID][levelID].vec_d;
                      nmiss = varrayNumMV(varList2[varID].gridsize, single, varList2[varID].missval);
                      cdoDefRecord(streamID2, varID, levelID);
                      cdoWriteRecord(streamID2, single.data(), nmiss);
                    }
                }
            }
        }

      tsID++;
    }

  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  vlistDestroy(vlistID2);

  cdoFinish();

  return nullptr;
}
