#ifndef POISSON_PROBLEM_H
#define POISSON_PROBLEM_H

#include <deal.II/base/function.h>

#include <deal.II/base/index_set.h>
#include <deal.II/base/logstream.h>
#include <deal.II/base/mpi_remote_point_evaluation.h>
#include <deal.II/base/point.h>
#include <deal.II/base/quadrature_lib.h>
#include <deal.II/base/template_constraints.h>
#include <deal.II/base/tensor.h>
#include <deal.II/base/utilities.h>

#include <deal.II/fe/mapping_q.h>
#include <deal.II/lac/affine_constraints.h>
#include <deal.II/lac/dynamic_sparsity_pattern.h>
#include <deal.II/lac/full_matrix.h>
#include <deal.II/lac/precondition.h>
#include <deal.II/lac/solver_cg.h>
#include <deal.II/lac/sparse_matrix.h>
#include <deal.II/lac/vector.h>

#include <deal.II/lac/block_sparse_matrix.h>
#include <deal.II/lac/block_sparsity_pattern.h>
#include <deal.II/lac/block_vector.h>
#include <deal.II/lac/solver_gmres.h>

#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/grid_out.h>
#include <deal.II/grid/grid_refinement.h>
#include <deal.II/grid/grid_tools.h>
#include <deal.II/grid/tria.h>

#include <deal.II/dofs/dof_handler.h>
#include <deal.II/dofs/dof_renumbering.h>
#include <deal.II/dofs/dof_tools.h>

#include <deal.II/fe/fe_q.h>
#include <deal.II/fe/fe_values.h>

#include <deal.II/numerics/data_out.h>
#include <deal.II/numerics/error_estimator.h>
#include <deal.II/numerics/fe_field_function.h>
#include <deal.II/numerics/matrix_tools.h>
#include <deal.II/numerics/solution_transfer.h>
#include <deal.II/numerics/vector_tools.h>

#include <deal.II/numerics/vector_tools_evaluate.h>
#include <deal.II/numerics/vector_tools_interpolate.h>
#include <deal.II/numerics/vector_tools_point_gradient.h>
#include <deal.II/numerics/vector_tools_point_value.h>
#include <fstream>
#include <functional>
#include <iostream>
#include <string>
#include <utility>
#include <vector>

#include "nufi/cells.h"
#include "nufi/grids.h"
#include "nufi/parameters.h"
#include "omp.h"

void save_space_vector(const std::vector<double> &vals,
                       const std::string &filename, size_t it);

using namespace dealii;

// =-=-=-=-= Poisson Solver =-=-=-=-=

template <int dim> class PoissonProblem {
public:
  PoissonProblem(unsigned int degree);

  void initialize();
  void solve_step();
  void coarse_and_refine_grid(size_t it);
  void run();

  unsigned int get_rhs_size();
  unsigned int get_dof_size();
  void set_rhs_function(
      std::function<std::vector<double>(const std::vector<Point<dim>> &)> f);
  // void set_rhs(const Vector<double> &new_rhs) { rhs = new_rhs; }

  const Vector<double> &get_solution() const { return solution.block(0); }
  const MappingQ<dim> &get_mapping() const { return mapping; }
  const DoFHandler<dim> &get_dof_handler() const { return dof_handler; }
  const Triangulation<dim> &get_triangulation() const { return triangulation; }
  const FE_Q<dim> &get_fe() const { return fe; }
  const CellLocator<dim> &get_locator() const { return cell_locator; }

  std::vector<double> sample_electric_field(double x_min, double x_max,
                                            unsigned int Nx);
  std::vector<double> sample_electric_potential(double x_min, double x_max,
                                                unsigned int Nx);

  std::vector<double>
  eval_vector_grad(const Vector<double> &solution,
                   const std::vector<Point<dim>> &points) const;

  void save_grid_to_file(std::string &filename) const;

  Triangulation<dim> triangulation;
  DoFHandler<dim> dof_handler;
  CellLocator<dim> cell_locator;

private:
  void create_mesh();
  void setup_system();
  void assemble_system();
  void solve();

  // Triangulation<dim> triangulation;
  FE_Q<dim> fe;
  // DoFHandler<dim> dof_handler;

  AffineConstraints<double> constraints;

  BlockSparseMatrix<double> system_matrix;

  BlockVector<double> solution;
  BlockVector<double> system_rhs;

  BlockSparsityPattern sparsity_pattern;

  std::function<std::vector<double>(const std::vector<Point<dim>> &)>
      rhs_function;
  // Vector<double> rhs;

  MappingQ<dim> mapping;

  // mutable std::vector<double> local_solution_buffer;
  // mutable std::unique_ptr<FEPointEvaluation<dim, dim>> evaluator;
};

//====//====//
// Utilities
//====//====//

template <int dim> unsigned int PoissonProblem<dim>::get_rhs_size() {

  QGauss<dim> quadrature_formula(fe.degree + 1);
  return quadrature_formula.size();
}

template <int dim> unsigned int PoissonProblem<dim>::get_dof_size() {
  return dof_handler.n_dofs();
}

template <int dim>
void PoissonProblem<dim>::set_rhs_function(
    std::function<std::vector<double>(const std::vector<Point<dim>> &)> f) {
  rhs_function = std::move(f);
}

template <int dim>
PoissonProblem<dim>::PoissonProblem(unsigned int degree)
    : triangulation(Triangulation<dim>::limit_level_difference_at_vertices),
      dof_handler(triangulation), fe(degree), mapping(degree) {}

template <int dim>
std::vector<double>
PoissonProblem<dim>::sample_electric_field(double x_min, double x_max,
                                           unsigned int Nx) {
  std::vector<double> E_values(Nx);

  const double dx = (x_max - x_min) / (Nx - 1);

  for (unsigned int i = 0; i < Nx; ++i) {
    const double x = x_min + i * dx;
    const Point<dim> point(x);

    // 1. Find the active cell containing x
    const auto cell_point_pair =
        GridTools::find_active_cell_around_point(mapping, dof_handler, point);

    const auto cell = cell_point_pair.first;
    const Point<dim> &unit_point = cell_point_pair.second;

    // 2. FEPointEvaluation expects an ArrayView of points
    std::vector<Point<dim>> points(1, unit_point);
    ArrayView<const Point<dim>> point_view(points);

    FEPointEvaluation<1, dim> evaluator(mapping, dof_handler.get_fe(),
                                        update_gradients);

    // reinit with ArrayView of points
    evaluator.reinit(cell, point_view);

    Vector<double> local_dofs(dof_handler.get_fe().dofs_per_cell);
    cell->get_dof_values(solution, local_dofs);

    // 3. Evaluate gradient at this point
    evaluator.evaluate(local_dofs, EvaluationFlags::gradients);

    const Tensor<1, dim> grad_phi = evaluator.get_gradient(0);

    // 4. Compute E = -grad(phi)
    E_values[i] = -grad_phi[0];
  }

  return E_values;
}

template <int dim>
std::vector<double>
PoissonProblem<dim>::sample_electric_potential(double x_min, double x_max,
                                               unsigned int Nx) {
  std::vector<double> values(Nx);
  std::vector<Point<dim>> eval_points(Nx);

  double Lx = x_max - x_min;
  double dx = Lx / Nx;

  for (unsigned int i = 0; i < Nx; ++i)
    eval_points[i] = Point<1, double>(x_min + i * dx);

  Utilities::MPI::RemotePointEvaluation<dim, dim> cache;
  cache.reinit(eval_points, triangulation, mapping);

  values = VectorTools::point_values<dim>(cache, dof_handler, solution);

  return values;
}

template <int dim>
std::vector<double>
eval_point_grad(const Mapping<dim> &mapping, const DoFHandler<dim> &dof_handler,
                const Vector<double> &solution, const Point<dim> &point) {
  Tensor Ex =
      VectorTools::point_gradient(mapping, dof_handler, solution, point);
  return Ex[0];
}

template <int dim>
std::vector<double> eval_vector_grad(const Mapping<dim> &mapping,
                                     const DoFHandler<dim> &dof_handler,
                                     const Vector<double> &solution,
                                     const std::vector<Point<dim>> &points) {
  size_t p_size = points.size();

  std::vector<double> Ex(p_size);
  for (size_t i = 0; i < p_size; ++i)
    Ex[i] = eval_point_grad(mapping, dof_handler, solution, points[i]);

  return Ex;
}

template <int dim>
double eval_point_value(const Mapping<dim> &mapping,
                        const DoFHandler<dim> &dof_handler,
                        const Vector<double> &solution,
                        const Point<dim> &point) {

  return VectorTools::point_value<dim>(mapping, dof_handler, solution, point);
}

template <int dim>
void PoissonProblem<dim>::save_grid_to_file(std::string &filename) const {
  GridOut grid_out;

  if (dim >= 2) {
    filename += ".svg";
    std::ofstream out(filename);
    grid_out.write_svg(triangulation, out);
  } else if (dim == 1) {
    filename += ".vtu";
    std::ofstream out(filename);
    grid_out.write_vtu(triangulation, out);
  }

  std::cout << "Grid written to " << filename << "\n";
}

//======//======//
// dealii Poisson
//======//======//
template <int dim> void PoissonProblem<dim>::create_mesh() {

  GridGenerator::hyper_cube(triangulation, Parameters::X_DOMAIN_LEFT,
                            Parameters::X_DOMAIN_RIGHT);

  std::vector<
      GridTools::PeriodicFacePair<typename Triangulation<dim>::cell_iterator>>
      periodic_faces;

  GridTools::collect_periodic_faces(triangulation, 0, 1, // boundary IDs
                                    0, periodic_faces);

  triangulation.add_periodicity(periodic_faces);

  triangulation.refine_global(Parameters::GLOBAL_REFINEMENT);
}

template <int dim> void PoissonProblem<dim>::setup_system() {
  dof_handler.distribute_dofs(fe);

  constraints.clear();

  DoFTools::make_hanging_node_constraints(dof_handler, constraints);

  DoFTools::make_periodicity_constraints(dof_handler, 0, 1, 0, constraints);

  constraints.close();

  std::vector<types::global_dof_index> dofs_per_block(2);

  dofs_per_block[0] = dof_handler.n_dofs();
  dofs_per_block[1] = 1;

  BlockDynamicSparsityPattern dsp(dofs_per_block, dofs_per_block);

  dsp.block(0, 0).reinit(dof_handler.n_dofs(), dof_handler.n_dofs());

  dsp.block(0, 1).reinit(dof_handler.n_dofs(), 1);

  dsp.block(1, 0).reinit(1, dof_handler.n_dofs());

  dsp.block(1, 1).reinit(1, 1);

  dsp.collect_sizes();

  DoFTools::make_sparsity_pattern(dof_handler, dsp.block(0, 0), constraints,
                                  false);

  // dense column m
  for (unsigned int i = 0; i < dof_handler.n_dofs(); ++i) {
    dsp.block(0, 1).add(i, 0);
    dsp.block(1, 0).add(0, i);
  }

  sparsity_pattern.copy_from(dsp);

  system_matrix.reinit(sparsity_pattern);

  solution.reinit(dofs_per_block);
  system_rhs.reinit(dofs_per_block);
}

template <int dim> void PoissonProblem<dim>::assemble_system() {
  system_matrix = 0;
  system_rhs = 0;

  const QGauss<dim> quadrature_formula(fe.degree + 1);

  FEValues<dim> fe_values(fe, quadrature_formula,
                          update_values | update_gradients |
                              update_quadrature_points | update_JxW_values);

  const unsigned int dofs_per_cell = fe.n_dofs_per_cell();
  const unsigned int n_q_points = quadrature_formula.size();

  FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell);

  Vector<double> cell_rhs(dofs_per_cell);

  std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);

  /*
   * First evaluate rho on all quadrature points.
   * Same strategy as your original implementation.
   */

  std::vector<Point<dim>> all_q_points;

  all_q_points.reserve(triangulation.n_active_cells() * n_q_points);

  for (const auto &cell : dof_handler.active_cell_iterators()) {
    fe_values.reinit(cell);

    const auto &points = fe_values.get_quadrature_points();

    all_q_points.insert(all_q_points.end(), points.begin(), points.end());
  }

  Assert(rhs_function, ExcMessage("Poisson RHS function not initialized"));

  std::vector<double> all_rho = rhs_function(all_q_points);

  Assert(all_rho.size() == all_q_points.size(),
         ExcMessage("rhs_function returned wrong size"));

  unsigned int q_offset = 0;

  // Assemble A and RHS

  for (const auto &cell : dof_handler.active_cell_iterators()) {

    fe_values.reinit(cell);

    cell_matrix = 0;
    cell_rhs = 0;

    for (unsigned int q = 0; q < n_q_points; ++q) {

      for (unsigned int i = 0; i < dofs_per_cell; ++i) {

        for (unsigned int j = 0; j < dofs_per_cell; ++j) {

          cell_matrix(i, j) += fe_values.shape_grad(i, q) *
                               fe_values.shape_grad(j, q) * fe_values.JxW(q);
        }

        cell_rhs(i) += fe_values.shape_value(i, q) * all_rho[q_offset + q] *
                       fe_values.JxW(q);
      }
    }

    q_offset += n_q_points;

    cell->get_dof_indices(local_dof_indices);

    /*
     * Put the local stiffness matrix
     * into block (0,0)
     */

    constraints.distribute_local_to_global(
        cell_matrix, cell_rhs, local_dof_indices, system_matrix.block(0, 0),
        system_rhs.block(0));
  }

  /*
   * Assemble mean(phi)=0 constraint:
   * m_i = integral(phi_i dx)
   * Add:
   * [ A  m ]
   * [mT 0 ]
   */

  for (const auto &cell : dof_handler.active_cell_iterators()) {

    fe_values.reinit(cell);

    cell->get_dof_indices(local_dof_indices);

    for (unsigned int q = 0; q < n_q_points; ++q) {

      for (unsigned int i = 0; i < dofs_per_cell; ++i) {

        const double value = fe_values.shape_value(i, q) * fe_values.JxW(q);

        const auto global_i = local_dof_indices[i];

        system_matrix.block(0, 1).add(global_i, 0, value);

        system_matrix.block(1, 0).add(0, global_i, value);
      }
    }
  }
}

template <int dim> void PoissonProblem<dim>::coarse_and_refine_grid(size_t it) {
  std::cout << "Refinement Started" << "\n";

  Vector<float> error_per_cell(triangulation.n_active_cells());
  KellyErrorEstimator<dim>::estimate(
      dof_handler, QGauss<dim - 1>(fe.degree + 1),
      std::map<types::boundary_id, const Function<dim> *>(), solution.block(0),
      error_per_cell);
  GridRefinement::refine_and_coarsen_fixed_number(triangulation, error_per_cell,
                                                  0.3, 0.03);

  triangulation.prepare_coarsening_and_refinement();

  SolutionTransfer<dim, Vector<double>> transfer(dof_handler);
  const Vector<double> refined_solution = solution.block(0);

  transfer.prepare_for_coarsening_and_refinement(refined_solution);

  triangulation.execute_coarsening_and_refinement();

  setup_system();

  transfer.interpolate(refined_solution, solution.block(0));

  solution.block(1) = 0;

  constraints.distribute(solution.block(0));

  std::cout << "Refinement Finished" << "\n";

  std::string grid_file_name =
      Parameters::PLOT_DIR + "grid_" + std::to_string(it);
  save_grid_to_file(grid_file_name);

  // std::vector<double> Ex =
  // sample_electric_potential(Parameters::X_DOMAIN_LEFT,
  //                                                    Parameters::X_DOMAIN_RIGHT,
  //                                                    Parameters::PLOT_NX);
  //
  // save_space_vector(Ex, "Ex_after_coarsed", it);
}

template <int dim> void PoissonProblem<dim>::solve() {
  SolverControl solver_control(20000, 1e-10);

  SolverGMRES<BlockVector<double>> solver(solver_control);

  solution = 0;

  solver.solve(system_matrix, solution, system_rhs, PreconditionIdentity());

  std::cout << "GMRES iterations = " << solver_control.last_step() << std::endl;

  constraints.distribute(solution.block(0));
}

template <int dim> void PoissonProblem<dim>::initialize() {
  create_mesh();  // build grid
  setup_system(); // distribute DoFs and matrices
}

template <int dim> void PoissonProblem<dim>::solve_step() {
  assemble_system();
  solve();
}

// NuFI doesnt use this, kept only for testing PoissonProblem
template <int dim> void PoissonProblem<dim>::run() {
  create_mesh();
  setup_system();
  assemble_system();
  solve();
}

#endif
