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

#include <dune/common/exceptions.hh>

#include <dune/matrix-vector/axpy.hh>

#include <dune/tectonic/utils/reductionfactors.hh>

#include "functionalfactory.hh"
#include "nonlinearsolver.hh"

#include "../utils/debugutils.hh"

#include "fixedpointiterator.hh"

void FixedPointIterationCounter::operator+=(
    FixedPointIterationCounter const &other) {
  iterations += other.iterations;
  multigridIterations += other.multigridIterations;
}

template <class Factory, class NBodyAssembler, class Updaters, class ErrorNorms>
FixedPointIterator<Factory, NBodyAssembler, Updaters, ErrorNorms>::FixedPointIterator(
    Dune::ParameterTree const &parset,
    const NBodyAssembler& nBodyAssembler,
    const IgnoreVector& ignoreNodes,
    GlobalFriction& globalFriction,
    const std::vector<const BitVector*>& bodywiseNonmortarBoundaries,
    const ErrorNorms& errorNorms)
    : parset_(parset),
      nBodyAssembler_(nBodyAssembler),
      ignoreNodes_(ignoreNodes),
      globalFriction_(globalFriction),
      bodywiseNonmortarBoundaries_(bodywiseNonmortarBoundaries),
      fixedPointMaxIterations_(parset.get<size_t>("v.fpi.maximumIterations")),
      fixedPointTolerance_(parset.get<double>("v.fpi.tolerance")),
      lambda_(parset.get<double>("v.fpi.lambda")),
      solverParset_(parset.sub("v.solver")),
      errorNorms_(errorNorms) {}

template <class Factory, class NBodyAssembler, class Updaters, class ErrorNorms>
template <class LinearSolver>
FixedPointIterationCounter
FixedPointIterator<Factory, NBodyAssembler, Updaters, ErrorNorms>::run(
    Updaters updaters, std::shared_ptr<LinearSolver>& linearSolver,
    const std::vector<Matrix>& velocityMatrices, const std::vector<Vector>& velocityRHSs,
    std::vector<Vector>& velocityIterates) {

  //std::cout << "FixedPointIterator::run()" << std::endl;

  const auto nBodies = nBodyAssembler_.nGrids();

  // debugging
  /*const auto& contactCouplings = nBodyAssembler_.getContactCouplings();
  for (size_t i=0; i<contactCouplings.size(); i++) {
    print(*contactCouplings[i]->nonmortarBoundary().getVertices(), "nonmortarBoundaries:");
  }*/

  FunctionalFactory<std::decay_t<decltype(nBodyAssembler_)>, decltype(globalFriction_), Matrix, Vector> functionalFactory(nBodyAssembler_, globalFriction_, velocityMatrices, velocityRHSs);
  functionalFactory.build();
  auto functional = functionalFactory.functional();

  NonlinearSolver<std::remove_reference_t<decltype(*functional)>, IgnoreVector> solver(parset_.sub("solver.tnnmg"), linearSolver, functional, ignoreNodes_);

  size_t fixedPointIteration;
  size_t multigridIterations = 0;
  std::vector<ScalarVector> alpha(nBodies);
  updaters.state_->extractAlpha(alpha);

  Vector totalVelocityIterate, old_v;
  nBodyAssembler_.nodalToTransformed(velocityIterates, totalVelocityIterate);
  old_v = totalVelocityIterate;

  for (fixedPointIteration = 0; fixedPointIteration < fixedPointMaxIterations_;
       ++fixedPointIteration) {

    //print(alpha, "alpha:");

    // contribution from nonlinearity
    globalFriction_.updateAlpha(alpha);

    auto res = solver.solve(solverParset_, totalVelocityIterate);

    nBodyAssembler_.postprocess(totalVelocityIterate, velocityIterates);
    //nBodyAssembler_.postprocess(totalVelocityIterate, velocityIterates);

    //print(totalVelocityIterate, "totalVelocityIterate:");
    //print(velocityIterates, "velocityIterates:");

    //DUNE_THROW(Dune::Exception, "Just need to stop here!");

    multigridIterations += res.iterations;

    Vector v_m = old_v;
    v_m *= 1.0 - lambda_;
    Dune::MatrixVector::addProduct(v_m, lambda_, totalVelocityIterate);

    // extract relative velocities in mortar basis
    std::vector<Vector> v_rel;
    split(v_m, v_rel);

    //print(v_m, "v_m: ");

    //print(v_rel, "v_rel");

    //std::cout << "- State problem set" << std::endl;

    // solve a state problem
    updaters.state_->solve(v_rel);

    //std::cout << "-- Solved" << std::endl;

    std::vector<ScalarVector> newAlpha(nBodies);
    updaters.state_->extractAlpha(newAlpha);

    //print(newAlpha, "new alpha:");

    bool breakCriterion = true;
    for (int i=0; i<nBodies; i++) {
        if (alpha[i].size()==0 || newAlpha[i].size()==0)
            continue;

        //print(alpha[i], "alpha i:");
        //print(newAlpha[i], "new alpha i:");
        if (errorNorms_[i]->diff(alpha[i], newAlpha[i]) >= fixedPointTolerance_) {
            breakCriterion = false;
            //std::cout << "fixedPoint error: " << errorNorms_[i]->diff(alpha[i], newAlpha[i]) << std::endl;
            break;
        }
    }

    //std::cout << fixedPointIteration << std::endl;

    if (lambda_ < 1e-12 or breakCriterion) {
      //std::cout << "-FixedPointIteration finished! " << (lambda_ < 1e-12 ? "lambda" : "breakCriterion") << std::endl;
      fixedPointIteration++;
      break;
    }
    alpha = newAlpha;
  }

  //TODO: recently added, might be wrong or superfluous
  globalFriction_.updateAlpha(alpha);

  //print(alpha, "alpha: ");

  //std::cout << "-FixedPointIteration finished with " << fixedPointIteration << " iterations, lambda " << lambda_ <<  "! " << std::endl;

  if (fixedPointIteration == fixedPointMaxIterations_)
    DUNE_THROW(Dune::Exception, "FPI failed to converge");

  updaters.rate_->postProcess(velocityIterates);

  // Cannot use return { fixedPointIteration, multigridIterations };
  // with gcc 4.9.2, see also http://stackoverflow.com/a/37777814/179927
  FixedPointIterationCounter ret;
  ret.iterations = fixedPointIteration;
  ret.multigridIterations = multigridIterations;
  return ret;
}

/*std::ostream &operator<<(std::ostream &stream,
                         FixedPointIterationCounter const &fpic) {
  return stream << "(" << fpic.iterations << "," << fpic.multigridIterations
                << ")";
}*/

template <class Factory, class NBodyAssembler, class Updaters, class ErrorNorms>
void FixedPointIterator<Factory, NBodyAssembler, Updaters, ErrorNorms>::split(
    const Vector& v,
    std::vector<Vector>& splitV) const {

    const size_t nBodies = nBodyAssembler_.nGrids();

    size_t globalIdx = 0;
    splitV.resize(nBodies);
    for (size_t bodyIdx=0; bodyIdx<nBodies; bodyIdx++) {
        auto& splitV_ = splitV[bodyIdx];

        splitV_.resize(nBodyAssembler_.grids_[bodyIdx]->size(dims));

        for (size_t i=0; i<splitV_.size(); i++) {
            splitV_[i] = v[globalIdx];
            globalIdx++;
        }
    }


   /*
        boundaryNodes =

        const auto gridView = contactCouplings[couplingIndices[0]]->nonmortarBoundary().gridView();

        Dune::MultipleCodimMultipleGeomTypeMapper<
            decltype(gridView), Dune::MCMGVertexLayout> const vertexMapper(gridView, Dune::mcmgVertexLayout());

        for (auto it = gridView.template begin<block_size>(); it != gridView.template end<block_size>(); ++it) {
            const auto i = vertexMapper.index(*it);

            for (size_t j=0; j<couplingIndices.size(); j++) {
                const auto couplingIdx = couplingIndices[j];

                if (not contactCouplings[couplingIdx]->nonmortarBoundary().containsVertex(i))
                  continue;

                localToGlobal_.emplace_back(i);
                restrictions_.emplace_back(weights[bodyIdx][i], weightedNormalStress[bodyIdx][i],
                                          couplings[i]->frictionData()(geoToPoint(it->geometry())));
                break;
            }

            globalIdx++;
        }
        maxIndex_[bodyIdx] = globalIdx;
    }*/
}

#include "fixedpointiterator_tmpl.cc"