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

      Gridcell   gridarea        Grid cell area in m^2
      Gridcell   gridweights     Grid cell weights
      Gridcell   gridmask        Grid mask
*/

#include <cdi.h>

#include "cdo_options.h"
#include "process_int.h"
#include "cdo_cdi_wrapper.h"
#include "cdo_zaxis.h"
#include <mpim_grid.h>
#include "constants.h"

static inline double
orthodrome(double px1, double py1, double px2, double py2)
{
  return std::acos(std::sin(py1) * std::sin(py2) + std::cos(py1) * std::cos(py2) * std::cos(px2 - px1));
}

double gridGetPlanetRadius(int gridID);

double
getPlanetRadius(int gridID)
{
  static auto radiusFromEnv = true;
  if (radiusFromEnv)
    {
      radiusFromEnv = false;
      auto envstr = getenv("PLANET_RADIUS");
      if (envstr)
        {
          const auto fval = atof(envstr);
          if (fval > 0) PlanetRadius = fval;
        }
    }

  auto planetRadius = PlanetRadius;

  const auto gridRadius = gridGetPlanetRadius(gridID);
  if (gridRadius > 1) planetRadius = gridRadius;

  return planetRadius;
}

void
grid_cell_area(int gridID, double *array)
{
  const auto gridtype = gridInqType(gridID);

  if (gridProjIsSupported(gridID) || gridtype == GRID_LONLAT || gridtype == GRID_GAUSSIAN
      || gridtype == GRID_GME || gridtype == GRID_CURVILINEAR
      || gridtype == GRID_UNSTRUCTURED || gridtype == GRID_GAUSSIAN_REDUCED)
    {
      if (gridHasArea(gridID))
        {
          if (Options::cdoVerbose) cdoPrint("Using existing grid cell area!");
          gridInqArea(gridID, array);
        }
      else
        {
          const int status = gridGenArea(gridID, array);
          if (status == 1)
            cdoAbort("%s: Cell corner coordinates missing!", __func__);
          else if (status == 2)
            cdoAbort("%s: Can't compute grid cell area for this grid!", __func__);

          const auto planetRadius = getPlanetRadius(gridID);
          if (Options::cdoVerbose) cdoPrint("Planet radius: %.2f", planetRadius);
          const auto ngp = gridInqSize(gridID);
          for (size_t i = 0; i < ngp; ++i) array[i] *= planetRadius * planetRadius;
        }
    }
  else
    {
      if (gridtype == GRID_GAUSSIAN_REDUCED)
        cdoAbort("Unsupported grid type: %s, use CDO option -R to convert reduced to regular grid!", gridNamePtr(gridtype));
      else
        cdoAbort("%s: Unsupported grid type: %s", __func__, gridNamePtr(gridtype));
    }
}

void *
Gridcell(void *process)
{
  cdoInitialize(process);

  // clang-format off
  const auto GRIDAREA    = cdoOperatorAdd("gridarea",     1,  0, nullptr);
  const auto GRIDWGTS    = cdoOperatorAdd("gridweights",  1,  0, nullptr);
  const auto GRIDMASK    = cdoOperatorAdd("gridmask",     0,  0, nullptr);
  const auto GRIDDX      = cdoOperatorAdd("griddx",       1,  0, nullptr);
  const auto GRIDDY      = cdoOperatorAdd("griddy",       1,  0, nullptr);
  const auto GRIDCELLIDX = cdoOperatorAdd("gridcellidx",  0,  0, nullptr);
  // clang-format on

  const auto operatorID = cdoOperatorID();

  operatorCheckArgc(0);

  // const bool needRadius = cdoOperatorF1(operatorID) > 0;

  const auto streamID1 = cdoOpenRead(0);
  const auto vlistID1 = cdoStreamInqVlist(streamID1);

  const auto ngrids = vlistNgrids(vlistID1);

  if (ngrids > 1) cdoWarning("Found more than 1 grid, using the first one!");

  auto gridID = vlistGrid(vlistID1, 0);
  const auto zaxisID = zaxisFromName("surface");

  const auto vlistID2 = vlistCreate();
  auto varID = vlistDefVar(vlistID2, gridID, zaxisID, TIME_CONSTANT);
  vlistDefNtsteps(vlistID2, 0);

  if (operatorID == GRIDAREA)
    {
      cdiDefKeyString(vlistID2, varID, CDI_KEY_NAME, "cell_area");
      cdiDefKeyString(vlistID2, varID, CDI_KEY_STDNAME, "area");
      cdiDefKeyString(vlistID2, varID, CDI_KEY_LONGNAME, "area of grid cell");
      cdiDefKeyString(vlistID2, varID, CDI_KEY_UNITS, "m2");
      vlistDefVarDatatype(vlistID2, varID, CDI_DATATYPE_FLT64);
    }
  else if (operatorID == GRIDWGTS)
    {
      cdiDefKeyString(vlistID2, varID, CDI_KEY_NAME, "cell_weights");
      vlistDefVarDatatype(vlistID2, varID, CDI_DATATYPE_FLT64);
    }
  else if (operatorID == GRIDMASK)
    {
      cdiDefKeyString(vlistID2, varID, CDI_KEY_NAME, "grid_mask");
      vlistDefVarDatatype(vlistID2, varID, CDI_DATATYPE_UINT8);
    }
  else if (operatorID == GRIDDX)
    {
      cdiDefKeyString(vlistID2, varID, CDI_KEY_NAME, "dx");
      cdiDefKeyString(vlistID2, varID, CDI_KEY_LONGNAME, "delta x");
      cdiDefKeyString(vlistID2, varID, CDI_KEY_UNITS, "m");
    }
  else if (operatorID == GRIDDY)
    {
      cdiDefKeyString(vlistID2, varID, CDI_KEY_NAME, "dy");
      cdiDefKeyString(vlistID2, varID, CDI_KEY_LONGNAME, "delta y");
      cdiDefKeyString(vlistID2, varID, CDI_KEY_UNITS, "m");
    }
  else if (operatorID == GRIDCELLIDX)
    {
      cdiDefKeyString(vlistID2, varID, CDI_KEY_NAME, "gridcellidx");
      cdiDefKeyString(vlistID2, varID, CDI_KEY_LONGNAME, "grid cell index");
      vlistDefVarDatatype(vlistID2, varID, CDI_DATATYPE_INT32);
    }

  const auto taxisID = cdoTaxisCreate(TAXIS_ABSOLUTE);
  vlistDefTaxis(vlistID2, taxisID);

  auto gridsize = gridInqSize(gridID);
  Varray<double> array(gridsize);

  if (operatorID == GRIDAREA)
    {
      grid_cell_area(gridID, &array[0]);
    }
  else if (operatorID == GRIDWGTS)
    {
      auto status = gridWeights(gridID, &array[0]);
      if (status != 0) cdoWarning("Grid cell bounds not available, using constant grid cell area weights!");
    }
  else if (operatorID == GRIDMASK)
    {
      std::vector<int> mask(gridsize);
      if (gridInqMask(gridID, nullptr))
        {
          gridInqMask(gridID, &mask[0]);
        }
      else
        {
          for (size_t i = 0; i < gridsize; ++i) mask[i] = 1;
        }

      for (size_t i = 0; i < gridsize; ++i) array[i] = mask[i];
    }
  else if (operatorID == GRIDCELLIDX)
    {
      for (size_t i = 0; i < gridsize; ++i) array[i] = i + 1;
    }
  else if (operatorID == GRIDDX || operatorID == GRIDDY)
    {
      const auto gridtype = gridInqType(gridID);
      if (gridProjIsSupported(gridID) || gridtype == GRID_LONLAT || gridtype == GRID_GAUSSIAN || gridtype == GRID_CURVILINEAR)
        {
          if (gridtype != GRID_CURVILINEAR) gridID = gridToCurvilinear(gridID, 1);

          gridsize = gridInqSize(gridID);
          const auto xsize = gridInqXsize(gridID);
          const auto ysize = gridInqYsize(gridID);

          if (!gridHasCoordinates(gridID)) cdoAbort("Cell center coordinates missing!");

          Varray<double> xv(gridsize), yv(gridsize);
          gridInqXvals(gridID, xv.data());
          gridInqYvals(gridID, yv.data());

          // Convert lat/lon units if required
          cdo_grid_to_radian(gridID, CDI_XAXIS, gridsize, &xv[0], "grid longitudes");
          cdo_grid_to_radian(gridID, CDI_YAXIS, gridsize, &yv[0], "grid latitudes");

          const auto planetRadius = getPlanetRadius(gridID);
          if (Options::cdoVerbose) cdoPrint("Planet radius: %.2f", planetRadius);

          double len1 = 0, len2 = 0;
          if (operatorID == GRIDDX)
            {
              for (size_t j = 0; j < ysize; ++j)
                for (size_t i = 0; i < xsize; ++i)
                  {
                    if (i == 0)
                      {
                        len2 = orthodrome(xv[j * xsize + i], yv[j * xsize + i], xv[j * xsize + i + 1], yv[j * xsize + i + 1]);
                        len1 = len2;
                      }
                    else if (i == (xsize - 1))
                      {
                        len1 = orthodrome(xv[j * xsize + i - 1], yv[j * xsize + i - 1], xv[j * xsize + i], yv[j * xsize + i]);
                        len2 = len1;
                      }
                    else
                      {
                        len1 = orthodrome(xv[j * xsize + i - 1], yv[j * xsize + i - 1], xv[j * xsize + i], yv[j * xsize + i]);
                        len2 = orthodrome(xv[j * xsize + i], yv[j * xsize + i], xv[j * xsize + i + 1], yv[j * xsize + i + 1]);
                      }

                    array[j * xsize + i] = 0.5 * (len1 + len2) * planetRadius;
                  }
            }
          else
            {
              for (size_t i = 0; i < xsize; ++i)
                for (size_t j = 0; j < ysize; ++j)
                  {
                    if (j == 0)
                      {
                        len2 = orthodrome(xv[j * xsize + i], yv[j * xsize + i], xv[(j + 1) * xsize + i], yv[(j + 1) * xsize + i]);
                        len1 = len2;
                      }
                    else if (j == (ysize - 1))
                      {
                        len1 = orthodrome(xv[(j - 1) * xsize + i], yv[(j - 1) * xsize + i], xv[j * xsize + i], yv[j * xsize + i]);
                        len2 = len1;
                      }
                    else
                      {
                        len1 = orthodrome(xv[(j - 1) * xsize + i], yv[(j - 1) * xsize + i], xv[j * xsize + i], yv[j * xsize + i]);
                        len2 = orthodrome(xv[j * xsize + i], yv[j * xsize + i], xv[(j + 1) * xsize + i], yv[(j + 1) * xsize + i]);
                      }

                    array[j * xsize + i] = 0.5 * (len1 + len2) * planetRadius;
                  }
            }
        }
      else
        {
          if (gridtype == GRID_GAUSSIAN_REDUCED)
            cdoAbort("Unsupported grid type: %s, use CDO option -R to convert reduced to regular grid!", gridNamePtr(gridtype));
          else
            cdoAbort("Unsupported grid type: %s", gridNamePtr(gridtype));
        }
    }

  const auto streamID2 = cdoOpenWrite(1);
  cdoDefVlist(streamID2, vlistID2);
  cdoDefTimestep(streamID2, 0);
  cdoDefRecord(streamID2, 0, 0);
  cdoWriteRecord(streamID2, &array[0], 0);

  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  cdoFinish();

  return nullptr;
}
