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

  Author: Uwe Schulzweida

*/

#include <atomic>
#include <algorithm> // std::sort

#include "process_int.h"
#include "cdo_wtime.h"
#include <mpim_grid.h>
#include "cdo_options.h"
#include "remap.h"
#include "remap_store_link.h"
#include "progress.h"
#include "cimdOmp.h"

// bicubic interpolation

static void
bicubic_set_weights(std::pair<double, double> ijCoords, double (&weights)[4][4])
{
  const auto iw = ijCoords.first;
  const auto jw = ijCoords.second;
  const auto iw1 = iw * iw * (iw - 1.0);
  const auto iw2 = iw * (iw - 1.0) * (iw - 1.0);
  const auto iw3 = iw * iw * (3.0 - 2.0 * iw);
  const auto jw1 = jw * jw * (jw - 1.0);
  const auto jw2 = jw * (jw - 1.0) * (jw - 1.0);
  const auto jw3 = jw * jw * (3.0 - 2.0 * jw);
  // clang-format off
  weights[0][0] = (1.0-jw3) * (1.0-iw3);
  weights[1][0] = (1.0-jw3) *      iw3;
  weights[2][0] =      jw3  *      iw3;
  weights[3][0] =      jw3  * (1.0-iw3);
  weights[0][1] = (1.0-jw3) *      iw2;
  weights[1][1] = (1.0-jw3) *      iw1;
  weights[2][1] =      jw3  *      iw1;
  weights[3][1] =      jw3  *      iw2;
  weights[0][2] =      jw2  * (1.0-iw3);
  weights[1][2] =      jw2  *      iw3;
  weights[2][2] =      jw1  *      iw3;
  weights[3][2] =      jw1  * (1.0-iw3);
  weights[0][3] =      jw2  *      iw2;
  weights[1][3] =      jw2  *      iw1;
  weights[2][3] =      jw1  *      iw1;
  weights[3][3] =      jw1  *      iw2;
  // clang-format on
}

int num_src_points(const Varray<short> &mask, const size_t (&searchIndices)[4], double (&src_lats)[4]);

static void
renormalize_weights(const double (&src_lats)[4], double (&weights)[4][4])
{
  // sum of weights for normalization
  const auto sumWeights = std::fabs(src_lats[0]) + std::fabs(src_lats[1]) + std::fabs(src_lats[2]) + std::fabs(src_lats[3]);
  for (int n = 0; n < 4; ++n) weights[n][0] = std::fabs(src_lats[n]) / sumWeights;
  for (int n = 0; n < 4; ++n) weights[n][1] = 0.0;
  for (int n = 0; n < 4; ++n) weights[n][2] = 0.0;
  for (int n = 0; n < 4; ++n) weights[n][3] = 0.0;
}

static void
bicubic_sort_weights(size_t (&searchIndices)[4], double (&weights)[4][4])
{
  constexpr size_t numWeights = 4;
  size_t n;
  for (n = 1; n < numWeights; ++n)
    if (searchIndices[n] < searchIndices[n - 1]) break;
  if (n == numWeights) return;

  struct IndexWeightX
  {
    size_t index;
    double weight[4];
  };

  std::array<IndexWeightX, numWeights> indexWeights;

  for (n = 0; n < numWeights; ++n)
    {
      indexWeights[n].index = searchIndices[n];
      for (int k = 0; k < 4; ++k) indexWeights[n].weight[k] = weights[n][k];
    }

  const auto comp_index = [](const auto &a, const auto &b) noexcept { return a.index < b.index; };
  std::sort(indexWeights.begin(), indexWeights.end(), comp_index);

  for (n = 0; n < numWeights; ++n)
    {
      searchIndices[n] = indexWeights[n].index;
      for (int k = 0; k < 4; ++k) weights[n][k] = indexWeights[n].weight[k];
    }
}

static void
bicubic_warning()
{
  static auto printWarning = true;

  if (Options::cdoVerbose || printWarning)
    {
      printWarning = false;
      cdo_warning("Bicubic interpolation failed for some grid points - used a distance-weighted average instead!");
    }
}

/*
  -----------------------------------------------------------------------

  This routine computes the weights for a bicubic interpolation.

  -----------------------------------------------------------------------
*/
void
remap_bicubic_weights(RemapSearch &rsearch, RemapVars &rv)
{
  auto srcGrid = rsearch.srcGrid;
  auto tgtGrid = rsearch.tgtGrid;

  if (Options::cdoVerbose) cdo_print("Called %s()", __func__);

  if (srcGrid->rank != 2) cdo_abort("Can't do bicubic interpolation if the source grid is not a regular 2D grid!");

  const auto start = Options::cdoVerbose ? cdo_get_wtime() : 0.0;

  progress::init();

  // Compute mappings from source to target grid

  auto tgtGridSize = tgtGrid->size;

  std::vector<WeightLinks4> weightLinks(tgtGridSize);
  weight_links_4_alloc(tgtGridSize, weightLinks);

  std::atomic<size_t> atomicCount{0};

  // Loop over target grid

#ifdef _OPENMP
#pragma omp parallel for default(shared)
#endif
  for (size_t tgtCellIndex = 0; tgtCellIndex < tgtGridSize; ++tgtCellIndex)
    {
      atomicCount++;
      if (cdo_omp_get_thread_num() == 0) progress::update(0, 1, (double)atomicCount / tgtGridSize);

      weightLinks[tgtCellIndex].nlinks = 0;

      if (!tgtGrid->mask[tgtCellIndex]) continue;

      const auto llpoint = remapgrid_get_lonlat(tgtGrid, tgtCellIndex);

      double src_lats[4];      //  latitudes  of four bilinear corners
      double src_lons[4];      //  longitudes of four bilinear corners
      double weights[4][4];    //  bicubic weights for four corners
      size_t searchIndices[4]; //  address for the four source points

      // Find nearest square of grid points on source grid
      auto searchResult = remap_search_square(rsearch, llpoint, searchIndices, src_lats, src_lons);

      // Check to see if points are mask points
      if (searchResult > 0)
        {
          for (int n = 0; n < 4; ++n)
            if (!srcGrid->mask[searchIndices[n]]) searchResult = 0;
        }

      // If point found, find local ijCoords coordinates for weights
      if (searchResult > 0)
        {
          tgtGrid->cell_frac[tgtCellIndex] = 1.0;

          const auto ijCoords = remap_find_weights(llpoint, src_lons, src_lats);
          if (ijCoords.first >= 0.0 && ijCoords.second >= 0.0)
            {
              // Successfully found ijCoords - compute weights
              bicubic_set_weights(ijCoords, weights);
              store_weightlinks_bicubic(searchIndices, weights, tgtCellIndex, weightLinks);
            }
          else
            {
              bicubic_warning();
              searchResult = -1;
            }
        }

      // Search for bicubic failed - use a distance-weighted average instead
      // (this is typically near the pole) Distance was stored in src_lats!
      if (searchResult < 0)
        {
          if (num_src_points(srcGrid->mask, searchIndices, src_lats) > 0)
            {
              tgtGrid->cell_frac[tgtCellIndex] = 1.0;
              renormalize_weights(src_lats, weights);
              store_weightlinks_bicubic(searchIndices, weights, tgtCellIndex, weightLinks);
            }
        }
    }

  progress::update(0, 1, 1);

  weight_links_4_to_remap_links(tgtGridSize, weightLinks, rv);

  if (Options::cdoVerbose) cdo_print("%s: %.2f seconds", __func__, cdo_get_wtime() - start);
}  // remap_bicubic_weights

/*
  -----------------------------------------------------------------------

  This routine computes and apply the weights for a bicubic interpolation.

  -----------------------------------------------------------------------
*/

template <typename T>
static T
bicubic_remap(const Varray<T> &srcArray, const double (&weights)[4][4], const size_t (&searchIndices)[4], const RemapGradients &gradients)
{
  const auto &glat = gradients.grad_lat;
  const auto &glon = gradients.grad_lon;
  const auto &glatlon = gradients.grad_latlon;

  double tgtPoint = 0.0;
  for (int n = 0; n < 4; ++n)
    tgtPoint += srcArray[searchIndices[n]] * weights[n][0] + glat[searchIndices[n]] * weights[n][1]
                 + glon[searchIndices[n]] * weights[n][2] + glatlon[searchIndices[n]] * weights[n][3];

  return tgtPoint;
}

template <typename T>
static void
remap_bicubic(RemapSearch &rsearch, const Varray<T> &srcArray, Varray<T> &tgtArray, T missval)
{
  auto srcGrid = rsearch.srcGrid;
  auto tgtGrid = rsearch.tgtGrid;

  if (Options::cdoVerbose) cdo_print("Called %s()", __func__);

  if (srcGrid->rank != 2) cdo_abort("Can't do bicubic interpolation if the source grid is not a regular 2D grid!");

  const auto start = Options::cdoVerbose ? cdo_get_wtime() : 0.0;

  progress::init();

  auto tgtGridSize = tgtGrid->size;
  auto srcGridSize = srcGrid->size;

  Varray<short> srcGridMask(srcGridSize);
  if (std::isnan(missval))
    {
#ifdef _OPENMP
#pragma omp parallel for default(shared) schedule(static)
#endif
      for (size_t i = 0; i < srcGridSize; ++i) srcGridMask[i] = !DBL_IS_EQUAL(srcArray[i], missval);
    }
  else
    {
#ifdef _OPENMP
#pragma omp parallel for default(shared) schedule(static)
#endif
      for (size_t i = 0; i < srcGridSize; ++i) srcGridMask[i] = !IS_EQUAL(srcArray[i], missval);
    }

  // Compute mappings from source to target grid

  RemapGradients gradients(srcGrid->size);
  remap_gradients(*srcGrid, srcGridMask, srcArray, gradients);

  std::atomic<size_t> atomicCount{0};

  // Loop over target grid

#ifdef _OPENMP
#pragma omp parallel for default(shared)
#endif
  for (size_t tgtCellIndex = 0; tgtCellIndex < tgtGridSize; ++tgtCellIndex)
    {
      atomicCount++;
      if (cdo_omp_get_thread_num() == 0) progress::update(0, 1, (double)atomicCount / tgtGridSize);

      tgtArray[tgtCellIndex] = missval;

      if (!tgtGrid->mask[tgtCellIndex]) continue;

      const auto llpoint = remapgrid_get_lonlat(tgtGrid, tgtCellIndex);

      double src_lats[4];      //  latitudes  of four bilinear corners
      double src_lons[4];      //  longitudes of four bilinear corners
      double weights[4][4];    //  bicubic weights for four corners
      size_t searchIndices[4]; //  address for the four source points

      // Find nearest square of grid points on source grid
      auto searchResult = remap_search_square(rsearch, llpoint, searchIndices, src_lats, src_lons);

      // Check to see if points are mask points
      if (searchResult > 0)
        {
          for (int n = 0; n < 4; ++n)
            if (!srcGridMask[searchIndices[n]]) searchResult = 0;
        }

      // If point found, find local ijCoords coordinates for weights
      if (searchResult > 0)
        {
          const auto ijCoords = remap_find_weights(llpoint, src_lons, src_lats);
          if (ijCoords.first >= 0.0 && ijCoords.second >= 0.0)
            {
              // Successfully found ijCoords - compute weights
              bicubic_set_weights(ijCoords, weights);
              bicubic_sort_weights(searchIndices, weights);
              tgtArray[tgtCellIndex] = bicubic_remap(srcArray, weights, searchIndices, gradients);
            }
          else
            {
              bicubic_warning();
              searchResult = -1;
            }
        }

      // Search for bicubic failed - use a distance-weighted average instead
      // (this is typically near the pole) Distance was stored in src_lats!
      if (searchResult < 0)
        {
          if (num_src_points(srcGridMask, searchIndices, src_lats) > 0)
            {
              renormalize_weights(src_lats, weights);
              bicubic_sort_weights(searchIndices, weights);
              tgtArray[tgtCellIndex] = bicubic_remap(srcArray, weights, searchIndices, gradients);
            }
        }
    }

  progress::update(0, 1, 1);

  if (Options::cdoVerbose) cdo_print("%s: %.2f seconds", __func__, cdo_get_wtime() - start);
}  // remap_bicubic

void
remap_bicubic(RemapSearch &rsearch, const Field &field1, Field &field2)
{
  if (field1.memType != field2.memType) cdo_abort("Interal error, memType of field1 and field2 differ!");

  if (field1.memType == MemType::Float)
    remap_bicubic(rsearch, field1.vec_f, field2.vec_f, (float) field1.missval);
  else
    remap_bicubic(rsearch, field1.vec_d, field2.vec_d, field1.missval);
}
