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

      Selbox     sellonlatbox    Select lon/lat box
      Selbox     selindexbox     Select index box
*/

#include <cdi.h>

#include "process_int.h"
#include "param_conversion.h"
#include <mpim_grid.h>

static void
shiftx(bool lcyclic, int nshift, int nx, int ny, const Varray<double> &array1, Varray<double> &array2, double missval)
{
  for (int i = 0; i < nx; i++)
    {
      bool is_cyclic = false;
      auto ins = i + nshift % nx;
      while (ins >= nx)
        {
          ins -= nx;
          is_cyclic = true;
        }
      while (ins < 0)
        {
          ins += nx;
          is_cyclic = true;
        }

      if (!lcyclic && is_cyclic)
        {
          for (int j = 0; j < ny; j++) array2[IX2D(j, ins, nx)] = missval;
        }
      else
        {
          for (int j = 0; j < ny; j++) array2[IX2D(j, ins, nx)] = array1[IX2D(j, i, nx)];
        }
    }
}

static void
shifty(bool lcyclic, int nshift, int nx, int ny, const Varray<double> &array1, Varray<double> &array2, double missval)
{
  for (int j = 0; j < ny; j++)
    {
      bool is_cyclic = false;
      auto jns = j + nshift % ny;

      while (jns >= ny)
        {
          jns -= ny;
          is_cyclic = true;
        }
      while (jns < 0)
        {
          jns += ny;
          is_cyclic = true;
        }

      if (!lcyclic && is_cyclic)
        {
          for (int i = 0; i < nx; i++) array2[IX2D(jns, i, nx)] = missval;
        }
      else
        {
          for (int i = 0; i < nx; i++) array2[IX2D(jns, i, nx)] = array1[IX2D(j, i, nx)];
        }
    }
}

static int
shiftx_coord(bool lcyclic, int nshift, int gridID1)
{
  const auto gridID2 = gridDuplicate(gridID1);

  const auto nx = gridInqXsize(gridID1);
  auto ny = gridInqYsize(gridID1);
  if (gridInqType(gridID1) != GRID_CURVILINEAR) ny = 1;

  Varray<double> array1(nx * ny), array2(nx * ny);
  gridInqXvals(gridID1, array1.data());
  shiftx(lcyclic, nshift, nx, ny, array1, array2, 0);
  gridDefXvals(gridID2, array2.data());

  if (gridInqXbounds(gridID1, nullptr))
    {
      const size_t nv = (gridInqType(gridID1) != GRID_CURVILINEAR) ? 2 : 4;

      Varray<double> bounds(nx * ny * nv);
      gridInqXbounds(gridID1, bounds.data());
      for (size_t k = 0; k < nv; ++k)
        {
          for (size_t i = 0; i < nx * ny; ++i) array1[i] = bounds[i * nv + k];
          shiftx(lcyclic, nshift, nx, ny, array1, array2, 0);
          for (size_t i = 0; i < nx * ny; ++i) bounds[i * nv + k] = array2[i];
        }
      gridDefXbounds(gridID2, bounds.data());
    }

  return gridID2;
}

static int
shifty_coord(bool lcyclic, int nshift, int gridID1)
{
  const auto gridID2 = gridDuplicate(gridID1);

  auto nx = gridInqXsize(gridID1);
  const auto ny = gridInqYsize(gridID1);
  if (gridInqType(gridID1) != GRID_CURVILINEAR) nx = 1;

  Varray<double> array1(nx * ny), array2(nx * ny);
  gridInqYvals(gridID1, array1.data());
  shifty(lcyclic, nshift, nx, ny, array1, array2, 0);
  gridDefYvals(gridID2, array2.data());

  if (gridInqYbounds(gridID1, nullptr))
    {
      const size_t nv = (gridInqType(gridID1) != GRID_CURVILINEAR) ? 2 : 4;

      Varray<double> bounds(nx * ny * nv);
      gridInqYbounds(gridID1, bounds.data());
      for (size_t k = 0; k < nv; ++k)
        {
          for (size_t i = 0; i < nx * ny; ++i) array1[i] = bounds[i * nv + k];
          shifty(lcyclic, nshift, nx, ny, array1, array2, 0);
          for (size_t i = 0; i < nx * ny; ++i) bounds[i * nv + k] = array2[i];
        }
      gridDefYbounds(gridID2, bounds.data());
    }

  return gridID2;
}

void *
Shiftxy(void *process)
{
  bool lcyclic = false;
  bool lcoord = false;
  int nrecs;
  int varID, levelID;
  size_t nmiss;

  cdoInitialize(process);

  const auto SHIFTX = cdoOperatorAdd("shiftx", 0, 0, nullptr);
  const auto SHIFTY = cdoOperatorAdd("shifty", 0, 0, nullptr);

  const auto operatorID = cdoOperatorID();

  int nshift = 1;
  if (operatorArgc() > 0)
    {
      nshift = parameter2int(cdoOperatorArgv(0));
      auto pargc = operatorArgc();
      auto pargv = cdoGetOperArgv();
      for (int ic = 1; ic < pargc; ++ic)
        {
          if (pargv[ic] == "cyclic")
            lcyclic = true;
          else if (pargv[ic] == "coord")
            lcoord = true;
        }
    }

  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 nvars = vlistNvars(vlistID1);
  std::vector<bool> vars(nvars);
  for (varID = 0; varID < nvars; varID++) vars[varID] = false;

  const auto ngrids = vlistNgrids(vlistID1);
  for (int index = 0; index < ngrids; index++)
    {
      const auto gridID1 = vlistGrid(vlistID1, index);
      const auto gridtype = gridInqType(gridID1);

      if (gridtype == GRID_LONLAT || gridtype == GRID_GAUSSIAN || gridtype == GRID_CURVILINEAR
          || (gridtype == GRID_PROJECTION && gridInqProjType(gridID1) == CDI_PROJ_RLL)
          || (gridtype == GRID_GENERIC && gridInqXsize(gridID1) > 0 && gridInqYsize(gridID1) > 0))
        {
          if (lcoord)
            {
              int gridID2 = -1;
              if (operatorID == SHIFTX)
                gridID2 = shiftx_coord(lcyclic, nshift, gridID1);
              else if (operatorID == SHIFTY)
                gridID2 = shifty_coord(lcyclic, nshift, gridID1);

              vlistChangeGridIndex(vlistID2, index, gridID2);
            }

          for (varID = 0; varID < nvars; varID++)
            if (gridID1 == vlistInqVarGrid(vlistID1, varID)) vars[varID] = true;
        }
      else if (gridtype == GRID_GENERIC && gridInqXsize(gridID1) <= 1 && gridInqYsize(gridID1) <= 1)
        {
        }
      else
        {
          cdoPrint("Unsupported grid type: %s", gridNamePtr(gridtype));
          if (gridtype == GRID_GAUSSIAN_REDUCED) cdoPrint("Use option -R to convert Gaussian reduced grid to a regular grid!");
          cdoAbort("Unsupported grid type!");
        }
    }

  for (varID = 0; varID < nvars; varID++)
    if (vars[varID]) break;

  if (varID >= nvars) cdoWarning("No variables selected!");

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

  const auto gridsizemax = vlistGridsizeMax(vlistID1);
  Varray<double> array1(gridsizemax), array2(gridsizemax);

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

      for (int recID = 0; recID < nrecs; recID++)
        {
          cdoInqRecord(streamID1, &varID, &levelID);
          cdoReadRecord(streamID1, array1.data(), &nmiss);

          cdoDefRecord(streamID2, varID, levelID);

          if (vars[varID])
            {
              const auto gridID1 = vlistInqVarGrid(vlistID1, varID);
              const auto gridsize = gridInqSize(gridID1);
              const auto missval = vlistInqVarMissval(vlistID2, varID);

              const auto nx = gridInqXsize(gridID1);
              const auto ny = gridInqYsize(gridID1);

              if (operatorID == SHIFTX)
                shiftx(lcyclic, nshift, nx, ny, array1, array2, missval);
              else if (operatorID == SHIFTY)
                shifty(lcyclic, nshift, nx, ny, array1, array2, missval);

              nmiss = varrayNumMV(gridsize, array2, missval);
              cdoWriteRecord(streamID2, array2.data(), nmiss);
            }
          else
            {
              cdoWriteRecord(streamID2, array1.data(), nmiss);
            }
        }
      tsID++;
    }

  cdoStreamClose(streamID2);
  cdoStreamClose(streamID1);

  vlistDestroy(vlistID2);

  cdoFinish();

  return nullptr;
}
