/*
  This file is part of CDO. CDO is a collection of Operators to
  manipulate and analyse Climate model Data.

  Copyright (C) 2003-2021 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:

      Invert     invertlat       Invert latitude
      Invert     invertlon       Invert longitude
      Invert     invertlatdes    Invert latitude description
      Invert     invertlondes    Invert longitude description
      Invert     invertlatdata   Invert latitude data
      Invert     invertlondata   Invert longitude data
*/

#include <cdi.h>

#include "process_int.h"

static void
invertLonDes(int vlistID)
{
  const auto ngrids = vlistNgrids(vlistID);
  for (int index = 0; index < ngrids; index++)
    {
      const auto gridID1 = vlistGrid(vlistID, index);
      const auto gridID2 = gridDuplicate(gridID1);

      const auto gridtype = gridInqType(gridID1);

      if (!(gridtype == GRID_GENERIC || gridtype == GRID_GAUSSIAN || gridtype == GRID_PROJECTION || gridtype == GRID_LONLAT
            || gridtype == GRID_CURVILINEAR))
        cdo_abort("Unsupported gridtype: %s!", gridNamePtr(gridtype));

      if (gridInqXvals(gridID1, nullptr))
        {
          const auto nlon = gridInqXsize(gridID1);
          const auto nlat = gridInqYsize(gridID1);
          const auto size = (gridtype == GRID_CURVILINEAR) ? nlon * nlat : nlon;

          Varray<double> xv1(size), xv2(size);

          gridInqXvals(gridID1, xv1.data());

          if (gridtype == GRID_CURVILINEAR)
            {
              for (size_t ilat = 0; ilat < nlat; ilat++)
                for (size_t ilon = 0; ilon < nlon; ilon++) xv2[ilat * nlon + nlon - ilon - 1] = xv1[ilat * nlon + ilon];
            }
          else
            {
              for (size_t ilon = 0; ilon < nlon; ilon++) xv2[nlon - ilon - 1] = xv1[ilon];
            }

          gridDefXvals(gridID2, xv2.data());
        }

      if (gridInqXbounds(gridID1, nullptr))
        {
          const auto nlon = gridInqXsize(gridID1);
          const auto nlat = gridInqYsize(gridID1);
          const auto nv = gridInqNvertex(gridID1);
          const auto size = (gridtype == GRID_CURVILINEAR) ? nv * nlon * nlat : nv * nlon;

          Varray<double> xb1(size), xb2(size);

          gridInqXbounds(gridID1, xb1.data());

          if (gridtype == GRID_CURVILINEAR)
            {
              for (size_t ilat = 0; ilat < nlat; ilat++)
                for (size_t ilon = 0; ilon < nlon; ilon++)
                  for (int iv = 0; iv < nv; iv++)
                    xb2[ilat * nlon * nv + (nlon - ilon - 1) * nv + iv] = xb1[ilat * nlon * nv + ilon * nv + iv];
            }
          else
            {
              for (size_t ilon = 0; ilon < nlon; ilon++)
                {
                  xb2[nlon * 2 - ilon * 2 - 1] = xb1[ilon * 2];
                  xb2[nlon * 2 - ilon * 2 - 2] = xb1[ilon * 2 + 1];
                }
            }

          gridDefXbounds(gridID2, xb2.data());
        }

      vlistChangeGrid(vlistID, gridID1, gridID2);
    }
}

static void
invertLatCoord(int gridID)
{
  const auto gridtype = gridInqType(gridID);

  if (gridInqYvals(gridID, nullptr))
    {
      const auto nlon = gridInqXsize(gridID);
      const auto nlat = gridInqYsize(gridID);
      const auto size = (gridtype == GRID_CURVILINEAR) ? nlon * nlat : nlat;

      Varray<double> yv1(size), yv2(size);

      if (gridtype == GRID_CURVILINEAR)
        {
          gridInqXvals(gridID, yv1.data());

          for (size_t ilat = 0; ilat < nlat; ilat++)
            for (size_t ilon = 0; ilon < nlon; ilon++) yv2[(nlat - ilat - 1) * nlon + ilon] = yv1[ilat * nlon + ilon];

          gridDefXvals(gridID, yv2.data());

          gridInqYvals(gridID, yv1.data());

          for (size_t ilat = 0; ilat < nlat; ilat++)
            for (size_t ilon = 0; ilon < nlon; ilon++) yv2[(nlat - ilat - 1) * nlon + ilon] = yv1[ilat * nlon + ilon];

          gridDefYvals(gridID, yv2.data());
        }
      else
        {
          gridInqYvals(gridID, yv1.data());

          for (size_t ilat = 0; ilat < nlat; ilat++) yv2[nlat - ilat - 1] = yv1[ilat];

          gridDefYvals(gridID, yv2.data());
        }
    }

  if (gridInqYbounds(gridID, nullptr))
    {
      const auto nlon = gridInqXsize(gridID);
      const auto nlat = gridInqYsize(gridID);
      const auto nv = gridInqNvertex(gridID);
      const auto size = (gridtype == GRID_CURVILINEAR) ? nv * nlon * nlat : nv * nlat;

      Varray<double> yb1(size), yb2(size);

      gridInqYbounds(gridID, yb1.data());

      if (gridtype == GRID_CURVILINEAR)
        {
          for (size_t ilat = 0; ilat < nlat; ilat++)
            for (size_t ilon = 0; ilon < nlon; ilon++)
              for (int iv = 0; iv < nv; iv++)
                yb2[(nlat - ilat - 1) * nlon * nv + ilon * nv + iv] = yb1[ilat * nlon * nv + ilon * nv + iv];
        }
      else
        {
          for (size_t ilat = 0; ilat < nlat; ilat++)
            {
              yb2[nlat * 2 - ilat * 2 - 1] = yb1[ilat * 2];
              yb2[nlat * 2 - ilat * 2 - 2] = yb1[ilat * 2 + 1];
            }
        }

      gridDefYbounds(gridID, yb2.data());
    }
}

static void
invertLatDes(int vlistID)
{
  const auto ngrids = vlistNgrids(vlistID);
  for (int index = 0; index < ngrids; index++)
    {
      const auto gridID1 = vlistGrid(vlistID, index);
      const auto gridID2 = gridDuplicate(gridID1);

      const auto gridtype = gridInqType(gridID1);

      if (!(gridtype == GRID_GENERIC || gridtype == GRID_GAUSSIAN || gridtype == GRID_PROJECTION || gridtype == GRID_LONLAT
            || gridtype == GRID_CURVILINEAR))
        cdo_abort("Unsupported gridtype: %s!", gridNamePtr(gridtype));

      invertLatCoord(gridID2);

      const auto projID = gridInqProj(gridID2);
      if (projID != CDI_UNDEFID) invertLatCoord(projID);

      vlistChangeGrid(vlistID, gridID1, gridID2);
    }
}

static void
invertLonData(double *array1, double *array2, int gridID1)
{
  const auto nlon = gridInqXsize(gridID1);
  const auto nlat = gridInqYsize(gridID1);

  if (nlat > 0)
    {
      std::vector<double *> field1(nlat), field2(nlat);

      for (size_t ilat = 0; ilat < nlat; ilat++)
        {
          field1[ilat] = array1 + ilat * nlon;
          field2[ilat] = array2 + ilat * nlon;
        }

      for (size_t ilat = 0; ilat < nlat; ilat++)
        for (size_t ilon = 0; ilon < nlon; ilon++) field2[ilat][nlon - ilon - 1] = field1[ilat][ilon];
    }
  else
    {
      array2[0] = array1[0];
    }
}

static void
invertLatData(double *array1, double *array2, int gridID1)
{
  const auto nlon = gridInqXsize(gridID1);
  const auto nlat = gridInqYsize(gridID1);

  if (nlat > 0)
    {
      std::vector<double *> field1(nlat), field2(nlat);

      for (size_t ilat = 0; ilat < nlat; ilat++)
        {
          field1[ilat] = array1 + ilat * nlon;
          field2[ilat] = array2 + ilat * nlon;
        }

      for (size_t ilat = 0; ilat < nlat; ilat++) array_copy(nlon, field1[ilat], field2[nlat - ilat - 1]);
    }
  else
    {
      array2[0] = array1[0];
    }
}

void *
Invert(void *process)
{
  enum
  {
    func_fld,
    func_all,
    func_hrd,
    func_lon,
    func_lat
  };

  cdo_initialize(process);

  // clang-format off
  cdo_operator_add("invertlat",     func_all, func_lat, nullptr);
  cdo_operator_add("invertlon",     func_all, func_lon, nullptr);
  cdo_operator_add("invertlatdes",  func_hrd, func_lat, nullptr);
  cdo_operator_add("invertlondes",  func_hrd, func_lon, nullptr);
  cdo_operator_add("invertlatdata", func_fld, func_lat, nullptr);
  cdo_operator_add("invertlondata", func_fld, func_lon, nullptr);
  // clang-format on

  const auto operatorID = cdo_operator_id();
  const auto operfunc1 = cdo_operator_f1(operatorID);
  const auto operfunc2 = cdo_operator_f2(operatorID);

  operator_check_argc(0);

  const auto streamID1 = cdo_open_read(0);

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

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

  if (operfunc1 == func_all || operfunc1 == func_hrd)
    {
      if (operfunc2 == func_lat)
        invertLatDes(vlistID2);
      else
        invertLonDes(vlistID2);
    }

  const auto streamID2 = cdo_open_write(1);

  cdo_def_vlist(streamID2, vlistID2);

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

  int tsID = 0;
  while (true)
    {
      const auto nrecs = cdo_stream_inq_timestep(streamID1, tsID);
      if (nrecs == 0) break;

      cdo_taxis_copy_timestep(taxisID2, taxisID1);

      cdo_def_timestep(streamID2, tsID);

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

          cdo_def_record(streamID2, varID, levelID);

          if (operfunc1 == func_all || operfunc1 == func_fld)
            {
              const auto gridID1 = vlistInqVarGrid(vlistID1, varID);

              if (operfunc2 == func_lat)
                invertLatData(array1.data(), array2.data(), gridID1);
              else
                invertLonData(array1.data(), array2.data(), gridID1);

              cdo_write_record(streamID2, array2.data(), nmiss);
            }
          else
            {
              cdo_write_record(streamID2, array1.data(), nmiss);
            }
        }
      tsID++;
    }

  cdo_stream_close(streamID2);
  cdo_stream_close(streamID1);

  cdo_finish();

  return nullptr;
}
