/*
  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 "remap.h"
#include "remap_store_link.h"
#include "cdo_options.h"
#include "progress.h"
#include "cimdOmp.h"

// bilinear interpolation

static inline void
limit_dphi_bounds(double &dphi)
{
  if (dphi > 3.0 * PIH) dphi -= PI2;
  if (dphi < -3.0 * PIH) dphi += PI2;
}

std::pair<double, double>
remap_find_weights(const LonLatPoint &llpoint, const double (&src_lons)[4], const double (&src_lats)[4])
{
  constexpr double converge = 1.0e-10;  // Convergence criterion
  extern long remap_max_iter;

  // Iterate to find iw,jw for bilinear approximation

  // some latitude  differences
  const auto dth1 = src_lats[1] - src_lats[0];
  const auto dth2 = src_lats[3] - src_lats[0];
  const auto dth3 = src_lats[2] - src_lats[1] - dth2;

  // some longitude differences
  auto dph1 = src_lons[1] - src_lons[0];
  auto dph2 = src_lons[3] - src_lons[0];
  auto dph3 = src_lons[2] - src_lons[1];

  limit_dphi_bounds(dph1);
  limit_dphi_bounds(dph2);
  limit_dphi_bounds(dph3);

  dph3 -= dph2;

  // current guess for bilinear coordinate
  double iguess = 0.5;
  double jguess = 0.5;

  long iter = 0;  // iteration counters
  for (iter = 0; iter < remap_max_iter; ++iter)
    {
      const auto dthp = llpoint.lat - src_lats[0] - dth1 * iguess - dth2 * jguess - dth3 * iguess * jguess;
      auto dphp = llpoint.lon - src_lons[0];

      limit_dphi_bounds(dphp);

      dphp -= dph1 * iguess + dph2 * jguess + dph3 * iguess * jguess;

      const auto mat1 = dth1 + dth3 * jguess;
      const auto mat2 = dth2 + dth3 * iguess;
      const auto mat3 = dph1 + dph3 * jguess;
      const auto mat4 = dph2 + dph3 * iguess;

      const auto determinant = mat1 * mat4 - mat2 * mat3;

      const auto deli = (dthp * mat4 - dphp * mat2) / determinant;
      const auto delj = (dphp * mat1 - dthp * mat3) / determinant;

      if (std::fabs(deli) < converge && std::fabs(delj) < converge) break;

      iguess += deli;
      jguess += delj;
    }

  if (iter >= remap_max_iter) iguess = jguess = -1.0;

  return std::pair<double, double>{iguess, jguess};
}

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

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

  for (int n = 0; n < 4; ++n)
    {
      if (mask[searchIndices[n]] != 0)
        icount++;
      else
        src_lats[n] = 0.;
    }

  return icount;
}

static void
renormalize_weights(const double (&src_lats)[4], double (&weights)[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] = std::fabs(src_lats[n]) / sumWeights;
}

static void
bilinear_sort_weights(size_t (&searchIndices)[4], double (&weights)[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;
  };

  std::array<IndexWeightX, numWeights> indexWeights;

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

  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;
      weights[n] = indexWeights[n].weight;
    }
}

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

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

// This routine computes the weights for a bilinear interpolation.
void
remap_bilinear_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 bilinear 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<WeightLinks> weightLinks(tgtGridSize);
  weight_links_alloc(4, tgtGridSize, weightLinks);

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

  // Loop over target grid

#ifdef _OPENMP
#pragma omp parallel for default(shared) schedule(static)
#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];       //  bilinear 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
              bilinear_set_weights(ijCoords, weights);
              store_weightlinks(0, 4, searchIndices, weights, tgtCellIndex, weightLinks);
            }
          else
            {
              bilinear_warning();
              searchResult = -1;
            }
        }

      /*
        Search for bilinear 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(0, 4, searchIndices, weights, tgtCellIndex, weightLinks);
            }
        }
    }

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

  weight_links_to_remap_links(0, tgtGridSize, weightLinks, rv);

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

template <typename T>
static inline T
bilinear_remap(const Varray<T> &srcArray, const double (&weights)[4], const size_t (&searchIndices)[4])
{
  // *tgtPoint = 0.0;
  // for (int n = 0; n < 4; ++n) *tgtPoint += srcArray[searchIndices[n]]*weights[n];
  return srcArray[searchIndices[0]] * weights[0] + srcArray[searchIndices[1]] * weights[1]
         + srcArray[searchIndices[2]] * weights[2] + srcArray[searchIndices[3]] * weights[3];
}

// This routine computes and apply the weights for a bilinear interpolation.
template <typename T>
static void
remap_bilinear(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 bilinear 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

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

  // Loop over target grid

#ifdef _OPENMP
#pragma omp parallel for default(shared) schedule(static)
#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];       //  bilinear 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]] == 0) 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
              bilinear_set_weights(ijCoords, weights);
              bilinear_sort_weights(searchIndices, weights);
              tgtArray[tgtCellIndex] = bilinear_remap(srcArray, weights, searchIndices);
            }
          else
            {
              bilinear_warning();
              searchResult = -1;
            }
        }

      /*
        Search for bilinear 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);
              bilinear_sort_weights(searchIndices, weights);
              tgtArray[tgtCellIndex] = bilinear_remap(srcArray, weights, searchIndices);
            }
        }
    }

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

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

void
remap_bilinear(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_bilinear(rsearch, field1.vec_f, field2.vec_f, (float) field1.missval);
  else
    remap_bilinear(rsearch, field1.vec_d, field2.vec_d, field1.missval);
}
