/*
  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 missval = field3D[0].missval;
  auto &data2D = field2D.vec_d;

  auto nmiss = field3D[0].nmiss;
  for (long k = 1; k < nlev1; ++k) nmiss += field3D[k].nmiss;

  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);
}

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

  auto nmiss = field3D[0].nmiss;
  for (long k = 1; k < nlev1; ++k) nmiss += field3D[k].nmiss;

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

      for (long k = 0; k < nlev1; ++k)
        {
          const auto val = field3D[k].vec_d[i];
          if (!DBL_IS_EQUAL(val, missval))
            {
              data2D[i] = val;
              break;
            }
        }
    }

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

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

  auto nmiss = field3D[0].nmiss;
  for (long k = 1; k < nlev1; ++k) nmiss += field3D[k].nmiss;

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

      for (long k = nlev1 - 1; k >= 0; --k)
        {
          const auto val = field3D[k].vec_d[i];
          if (!DBL_IS_EQUAL(val, missval))
            {
              data2D[i] = val;
              break;
            }
        }
    }

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

static bool
positiveIsDown(int zaxisID)
{
  return zaxisInqPositive(zaxisID) == 2;
}

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

  cdoInitialize(process);

  // clang-format off
  const auto ISOSURFACE  = cdoOperatorAdd("isosurface",  0,  0, nullptr);
  const auto BOTTOMVALUE = cdoOperatorAdd("bottomvalue", 0,  0, nullptr);
  const auto TOPVALUE    = cdoOperatorAdd("topvalue",    0,  0, nullptr);
  // clang-format on

  const auto operatorID = cdoOperatorID();

  double isoval = 0.0;
  if (operatorID == ISOSURFACE)
    {
      operatorInputArg("isoval");
      operatorCheckArgc(1);
      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.data());

  const auto lpositive = !(lev1[0] < 0.0 && lev1[nlev1 - 1] < 0.0);
  const auto lreverse = (lev1[0] > lev1[nlev1 - 1]);
  auto bottomValueFunc = lreverse ? layerValueMax : layerValueMin;
  auto topValueFunc = lreverse ? layerValueMin : layerValueMax;
  if (lpositive && positiveIsDown(zaxisID1)) std::swap(bottomValueFunc, topValueFunc);

  const auto 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> lvar3D(nvars), vars(nvars);
  FieldVector2D vars1;
  fieldsFromVlist(vlistID1, vars1, FIELD_VEC);

  for (int varID = 0; varID < nvars; varID++) lvar3D[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(), &vars1[varID][levelID].nmiss);
          vars[varID] = true;
        }

      for (int varID = 0; varID < nvars; varID++)
        {
          if (vars[varID])
            {
              if (lvar3D[varID])
                {
                  if (operatorID == ISOSURFACE)
                    isosurface(isoval, nlev1, lev1, vars1[varID], field);
                  else if (operatorID == BOTTOMVALUE)
                    bottomValueFunc(nlev1, lev1, vars1[varID], field);
                  else if (operatorID == TOPVALUE)
                    topValueFunc(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;
                      const auto 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;
}
