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

  Author: Uwe Schulzweida

*/

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#ifdef HAVE_LIBFFTW3
#include <fftw3.h>
#include <mutex>
static std::mutex fftwMutex;
#endif

#include <cdi.h>

#include "process_int.h"
#include "param_conversion.h"
#include "cdo_alloc.h"
#include "cdo_fft.h"
#include "cdo_math.h"
#include "cdo_options.h"
#include "cdo_omp.h"
#include "field_functions.h"

namespace
{
#ifdef HAVE_LIBFFTW3
struct FFTW3Memory
{
  fftw_complex *in_fft{};
  fftw_complex *out_fft{};
  fftw_plan plan{};

  bool
  empty() const
  {
    return (in_fft == nullptr);
  }

  void
  resize(int numSteps, int sign)
  {
    in_fft = fftw_alloc_complex(numSteps);
    out_fft = fftw_alloc_complex(numSteps);
    std::scoped_lock lock(fftwMutex);
    plan = fftw_plan_dft_1d(numSteps, in_fft, out_fft, sign, FFTW_ESTIMATE);
  }

  FFTW3Memory() {}
  ~FFTW3Memory()
  {
    if (plan)
    {
      std::scoped_lock lock(fftwMutex);
      fftw_destroy_plan(plan);
    }
    if (in_fft) fftw_free(in_fft);
    if (out_fft) fftw_free(out_fft);
  }
};
#endif

struct FourierMemory
{
  std::vector<double> real;
  std::vector<double> imag;
  std::vector<double> work_r;
  std::vector<double> work_i;

  bool
  empty() const
  {
    return (real.empty());
  }

  void
  resize(int numSteps)
  {
    real.resize(numSteps);
    imag.resize(numSteps);
    if (!cdo::is_power_of_two(numSteps))
    {
      work_r.resize(numSteps);
      work_i.resize(numSteps);
    }
  }
};
}  // namespace

static void
fourier_fftw3(int sign, int varID, int levelID, int numSteps, size_t gridsize, double missval, FieldVector3D &vars)
{
  (void) sign;
#ifdef HAVE_LIBFFTW3
  auto norm = 1.0 / std::sqrt(numSteps);

  std::vector<FFTW3Memory> fmPool(Threading::ompNumMaxThreads);

#ifdef _OPENMP
#pragma omp parallel for default(shared) schedule(static)
#endif
  for (size_t i = 0; i < gridsize; ++i)
  {
    auto tid = (Threading::ompNumMaxThreads == 1) ? 0 : cdo_omp_get_thread_num();
    auto &fm = fmPool[tid];
    if (fm.empty()) fm.resize(numSteps, sign);

    auto hasMissvals = false;
    for (int t = 0; t < numSteps; ++t)
    {
      auto real = vars[t][varID][levelID].vec_d[2 * i];
      auto imag = vars[t][varID][levelID].vec_d[2 * i + 1];
      fm.in_fft[t][0] = real;
      fm.in_fft[t][1] = imag;
      if (fp_is_equal(real, missval) || fp_is_equal(imag, missval)) { hasMissvals = true; }
    }

    if (hasMissvals)
    {
      for (int t = 0; t < numSteps; ++t)
      {
        vars[t][varID][levelID].vec_d[2 * i] = missval;
        vars[t][varID][levelID].vec_d[2 * i + 1] = missval;
      }
    }
    else
    {
      fftw_execute(fm.plan);

      for (int t = 0; t < numSteps; ++t)
      {
        vars[t][varID][levelID].vec_d[2 * i] = fm.out_fft[t][0] * norm;
        vars[t][varID][levelID].vec_d[2 * i + 1] = fm.out_fft[t][1] * norm;
      }
    }
  }

  if (Options::cdoVerbose) fftw_print_plan(fmPool[0].plan);
#endif
}

static void
fourier_intrinsic(int sign, int varID, int levelID, int numSteps, size_t gridsize, double missval, FieldVector3D &vars)
{
  std::vector<FourierMemory> fmPool(Threading::ompNumMaxThreads);

#ifdef _OPENMP
#pragma omp parallel for default(shared) schedule(static)
#endif
  for (size_t i = 0; i < gridsize; ++i)
  {
    auto tid = (Threading::ompNumMaxThreads == 1) ? 0 : cdo_omp_get_thread_num();
    auto &fm = fmPool[tid];
    if (fm.empty()) fm.resize(numSteps);

    auto hasMissvals = false;
    for (int t = 0; t < numSteps; ++t)
    {
      auto real = vars[t][varID][levelID].vec_d[2 * i];
      auto imag = vars[t][varID][levelID].vec_d[2 * i + 1];
      fm.real[t] = real;
      fm.imag[t] = imag;
      if (fp_is_equal(real, missval) || fp_is_equal(imag, missval)) { hasMissvals = true; }
    }

    if (hasMissvals)
    {
      for (int t = 0; t < numSteps; ++t)
      {
        vars[t][varID][levelID].vec_d[2 * i] = missval;
        vars[t][varID][levelID].vec_d[2 * i + 1] = missval;
      }
    }
    else
    {
      if (cdo::is_power_of_two(numSteps))  // numSteps is a power of 2
        cdo::fft(fm.real.data(), fm.imag.data(), numSteps, sign);
      else
        cdo::ft_r(fm.real.data(), fm.imag.data(), numSteps, sign, fm.work_r.data(), fm.work_i.data());

      for (int t = 0; t < numSteps; ++t)
      {
        vars[t][varID][levelID].vec_d[2 * i] = fm.real[t];
        vars[t][varID][levelID].vec_d[2 * i + 1] = fm.imag[t];
      }
    }
  }
}

class Fourier : public Process
{
public:
  using Process::Process;
  inline static CdoModule module = {
    .name = "Fourier",
    .operators = { { "fourier", FourierHelp } },
    .aliases = {},
    .mode = EXPOSED,     // Module mode: 0:intern 1:extern
    .number = CDI_COMP,  // Allowed number type
    .constraints = { 1, 1, NoRestriction },
  };
  inline static auto registration = RegisterEntry<Fourier>();

private:
  CdoStreamID streamID1;
  CdoStreamID streamID2;

  int taxisID1{ CDI_UNDEFID };
  int taxisID2{ CDI_UNDEFID };

  int vlistID1{ CDI_UNDEFID };

  bool useFFTW3 = false;
  int sign{};

  VarList varList;

public:
  void
  init() override
  {
    if (Options::Use_FFTW)
    {
#ifdef HAVE_LIBFFTW3
      if (Options::cdoVerbose) cdo_print("Using fftw3 lib");
      useFFTW3 = true;
#else
      if (Options::cdoVerbose) cdo_print("LIBFFTW3 support not compiled in!");
#endif
    }

    if (Options::cdoVerbose && !useFFTW3) cdo_print("Using intrinsic FFT function!");

    operator_input_arg("the sign of the exponent (-1 for normal or 1 for reverse transformation)!");
    sign = parameter_to_int(cdo_operator_argv(0));

    streamID1 = cdo_open_read(0);

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

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

    streamID2 = cdo_open_write(1);
    cdo_def_vlist(streamID2, vlistID2);

    varList = VarList(vlistID1);
  }

  void
  run() override
  {
    FieldVector3D varDataList;
    std::vector<CdiDateTime> vDateTimes;

    auto numVars = varList.numVars();
    int tsID = 0;
    while (true)
    {
      auto numFields = cdo_stream_inq_timestep(streamID1, tsID);
      if (numFields == 0) break;

      cdo::ensure_step_size(vDateTimes, tsID);
      cdo::ensure_step_size(varDataList, tsID);

      vDateTimes[tsID] = taxisInqVdatetime(taxisID1);

      field2D_init(varDataList[tsID], varList);

      for (int fieldID = 0; fieldID < numFields; ++fieldID)
      {
        auto [varID, levelID] = cdo_inq_field(streamID1);
        auto gridsize = varList.vars[varID].gridSize;
        varDataList[tsID][varID][levelID].resize(2 * gridsize);
        cdo_read_field(streamID1, varDataList[tsID][varID][levelID]);
      }

      tsID++;
    }

    int nts = tsID;

    for (int varID = 0; varID < numVars; ++varID)
    {
      auto const &var = varList.vars[varID];
      for (int levelID = 0; levelID < var.numLevels; ++levelID)
      {
        if (useFFTW3)
          fourier_fftw3(sign, varID, levelID, nts, var.gridSize, var.missval, varDataList);
        else
          fourier_intrinsic(sign, varID, levelID, nts, var.gridSize, var.missval, varDataList);
      }
    }

#ifdef HAVE_LIBFFTW3
    if (useFFTW3) { fftw_cleanup(); }
#endif

    for (tsID = 0; tsID < nts; ++tsID)
    {
      taxisDefVdatetime(taxisID2, vDateTimes[tsID]);
      cdo_def_timestep(streamID2, tsID);

      for (int varID = 0; varID < numVars; ++varID)
      {
        auto numLevels = varList.vars[varID].numLevels;
        for (int levelID = 0; levelID < numLevels; ++levelID)
        {
          if (!varDataList[tsID][varID][levelID].empty())
          {
            cdo_def_field(streamID2, varID, levelID);
            cdo_write_field(streamID2, varDataList[tsID][varID][levelID]);
          }
        }
      }
    }
  }

  void
  close() override
  {
    cdo_stream_close(streamID2);
    cdo_stream_close(streamID1);
  }
};
