// This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2020 Alec Jacobson <alecjacobson@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#include "facet_adjacency_matrix.h"
#include "unique_edge_map.h"

template <typename DerivedF, typename Atype>
IGL_INLINE void igl::facet_adjacency_matrix(
  const Eigen::MatrixBase<DerivedF> & F, Eigen::SparseMatrix<Atype> & A)
{
  using namespace Eigen;
  typedef typename DerivedF::Scalar Index;
  const auto m = F.rows();
  Eigen::Matrix<Index,Dynamic,1> EMAP,uEE,uEC;
  Eigen::Matrix<Index,Dynamic,2> E,uE;
  igl::unique_edge_map(F,E,uE,EMAP,uEC,uEE);
  std::vector<Eigen::Triplet<Index> > AIJV;
  AIJV.reserve(2*uE.rows());
  const Eigen::Index nu = uE.rows();
  for(Eigen::Index ue = 0;ue<nu;ue++)
  {
    // number of faces incident on this unique edge
    const Eigen::Index mue = uEC(ue+1)-uEC(ue);
    // base offset in uEE
    const Eigen::Index uECue = uEC(ue);
    assert(uECue < uEE.rows());
    for(Eigen::Index i = 0;i<mue;i++)
    {
      const auto ii = uEE(uECue+i)%m;
      for(Eigen::Index j = 0;j<mue;j++)
      {
        const auto jj = uEE(uECue+j)%m;
        if(ii != jj){ AIJV.emplace_back(ii,jj,1);}
      }
    }
  }
  // Facet Adjacency matrix (with (arbitrary) >0
  A.resize(m,m);
  A.setFromTriplets(AIJV.begin(),AIJV.end());
  // Set all non-zerro values to 1
  for(Eigen::Index g = 0;g<A.outerSize();g++)
  {
    for(typename Eigen::SparseMatrix<Atype>::InnerIterator it (A,g); it; ++it)
    {
      if(it.value()) it.valueRef() = 1;
    }
  }
}

#ifdef IGL_STATIC_LIBRARY
// Explicit template instantiation
// generated by autoexplicit.sh
template void igl::facet_adjacency_matrix<Eigen::Matrix<int, -1, -1, 0, -1, -1>, bool>(Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::SparseMatrix<bool, 0, int>&);
// generated by autoexplicit.sh
template void igl::facet_adjacency_matrix<Eigen::Matrix<int, -1, -1, 0, -1, -1>, int>(Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::SparseMatrix<int, 0, int>&);
#endif
