//=============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE.  See the above copyright notice for more information.
//=============================================================================

#include "smtk/io/Logger.h"

#include "smtk/session/aeva/CellSelection.h"
#include "smtk/session/aeva/Predicates.h"
#include "smtk/session/aeva/operators/ProximityFeature.h"

#include "smtk/model/Face.h"
#include "smtk/model/Model.h"

#include "smtk/attribute/Attribute.h"
#include "smtk/attribute/ComponentItem.h"
#include "smtk/attribute/DoubleItem.h"
#include "smtk/attribute/IntItem.h"
#include "smtk/attribute/VoidItem.h"

#include "smtk/operation/MarkGeometry.h"

#include "smtk/extension/paraview/appcomponents/pqSMTKBehavior.h"
#include "smtk/extension/paraview/appcomponents/pqSMTKWrapper.h"
#include "smtk/view/Selection.h"

#include "vtkCellData.h"
#include "vtkDataSetSurfaceFilter.h"
#include "vtkDistancePolyDataFilter.h"
#include "vtkDoubleArray.h"
#include "vtkImplicitPolyDataDistance.h"
#include "vtkMath.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkPolyDataNormals.h"
#include "vtkThreshold.h"
#include "vtkVector.h"
#include "vtkVectorOperators.h"

#include <cmath>

#include "smtk/session/aeva/ProximityFeature_xml.h"

// On Windows MSVC 2015+, something is included that defines
// a macro named ERROR to be 0. This causes smtkErrorMacro()
// to expand into garbage (because smtk::io::Logger::ERROR
// gets expanded to smtk::io::Logger::0).
#ifdef ERROR
#undef ERROR
#endif

using smtk::common::UUID;

namespace smtk
{
namespace session
{
namespace aeva
{

bool ProximityFeature::ableToOperate()
{
  if (!this->Superclass::ableToOperate())
  {
    return false;
  }

  auto target = this->parameters()->findComponent("target")->value();
  auto resource = std::dynamic_pointer_cast<smtk::session::aeva::Resource>(target->resource());
  auto session = resource ? resource->session() : smtk::session::aeva::Session::Ptr();
  if (!session)
  {
    return false;
  }

  return target && session->findStorage(target->id());
}

ProximityFeature::Result ProximityFeature::operateInternal()
{
  smtk::session::aeva::Resource::Ptr resource;
  smtk::session::aeva::Session::Ptr session;
  auto result = this->createResult(smtk::operation::Operation::Outcome::FAILED);
  this->prepareResourceAndSession(result, resource, session);

  auto maxDistance = this->parameters()->findDouble("distance")->value();
  auto target = this->parameters()->findComponent("target")->value();
  auto angleItem = this->parameters()->findDouble("angle");
  bool checkNormals = angleItem->isEnabled();
  double angle = angleItem->value();
  double angleTol = std::cos(vtkMath::RadiansFromDegrees(angle));

  vtkSmartPointer<vtkDataObject> targetData;
  if (!target || !(targetData = session->findStorage(target->id())))
  {
    smtkErrorMacro(this->log(), "No target available or target has no geometric data.");
  }

  // std::cout << "Cells " << maxDistance << " or closer to " << target->name() << "\n";
  vtkSmartPointer<vtkPolyData> targetSurf;
  vtkSmartPointer<vtkDataArray> targetSurfNormals;
  SurfaceWithNormals(targetData, targetSurf, targetSurfNormals);

  vtkNew<vtkImplicitPolyDataDistance> distanceToTarget;
  distanceToTarget->SetInput(targetSurf);

  auto assocs = this->parameters()->associations();
  auto created = result->findComponent("created");
  smtk::operation::MarkGeometry geomMarker(resource);
  for (const auto& assoc : *assocs)
  {
    auto data = session->findStorage(assoc->id());
    if (!data)
    {
      continue;
    }
    vtkSmartPointer<vtkPolyData> assocSurf;
    vtkSmartPointer<vtkDataArray> assocSurfNormals;
    SurfaceWithNormals(data, assocSurf, assocSurfNormals);

    vtkNew<vtkDoubleArray> selectionVals;
    selectionVals->SetName("SelectionValue");
    selectionVals->SetNumberOfTuples(assocSurf->GetNumberOfCells());
    vtkNew<vtkIdList> cellPoints;
    double minDistanceHit;
    double maxDistanceHit;
    for (vtkIdType ii = 0; ii < assocSurfNormals->GetNumberOfTuples(); ++ii)
    {
      assocSurf->GetCellPoints(ii, cellPoints);
      // Check whether any point is both close enough and has a normal pointing
      // opposite the associated surface's normal.
      bool pass = false;
      for (vtkIdType jj = 0; jj < cellPoints->GetNumberOfIds(); ++jj)
      {
        vtkVector3d pt;
        vtkVector3d targetPt;
        assocSurf->GetPoint(cellPoints->GetId(jj), pt.GetData());
        auto dist =
          distanceToTarget->EvaluateFunctionAndGetClosestPoint(pt.GetData(), targetPt.GetData());
        // Track the min/max distances in case no cells are selected.
        if (ii == 0 && jj == 0)
        {
          minDistanceHit = dist;
          maxDistanceHit = dist;
        }
        else
        {
          if (dist < minDistanceHit)
          {
            minDistanceHit = dist;
          }
          else if (dist > maxDistanceHit)
          {
            maxDistanceHit = dist;
          }
        }
        if (dist < maxDistance)
        {
          vtkIdType targetPtId = targetSurf->FindPoint(pt[0], pt[1], pt[2]);
          if (targetPtId >= 0)
          {
            if (checkNormals)
            {
              vtkVector3d tn;
              vtkVector3d an;
              targetSurfNormals->GetTuple(targetPtId, tn.GetData());
              assocSurfNormals->GetTuple(cellPoints->GetId(jj), an.GetData());
              if (an.Dot(tn) < -angleTol)
              {
                selectionVals->SetValue(ii, dist);
                pass = true;
                break;
              }
            }
            else
            {
              selectionVals->SetValue(ii, dist);
              pass = true;
              break;
            }
          }
        }
      }
      if (!pass)
      {
        selectionVals->SetValue(ii, 2 * maxDistance);
      }
    }
    assocSurf->GetCellData()->AddArray(selectionVals);

    vtkNew<vtkThreshold> threshold;
    threshold->SetInputDataObject(assocSurf);
    threshold->SetInputArrayToProcess(
      0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_CELLS, "SelectionValue");
    threshold->ThresholdBetween(-maxDistance, maxDistance);

    vtkNew<vtkDataSetSurfaceFilter> extractSurface;
    extractSurface->SetInputConnection(threshold->GetOutputPort());
    extractSurface->Update();
    vtkNew<vtkPolyData> geom;
    geom->ShallowCopy(extractSurface->GetOutput());
    // Must remove both sets of normals or rendering artifacts will occur
    // (z-fighting with point normals, bad shading with cell normals).
    geom->GetCellData()->RemoveArray("SelectionValue");
    geom->GetCellData()->RemoveArray("Normals");
    geom->GetPointData()->RemoveArray("Normals");

    if (geom->GetNumberOfCells() == 0)
    {
      smtkInfoMacro(this->log(),
        "No input or distance too small. Found distances in range [" << minDistanceHit << "  "
                                                                     << maxDistanceHit << "].");
    }

    auto* wrapper = pqSMTKBehavior::instance()->builtinOrActiveWrapper();
    if (wrapper)
    {
      auto cellSelection = CellSelection::create(resource, geom, this->manager());
      session->addStorage(cellSelection->id(), geom);
      created->appendValue(cellSelection);
      geomMarker.markModified(cellSelection);
      std::set<smtk::model::EntityPtr> selected;
      selected.insert(cellSelection);
      auto selection = wrapper->smtkSelection();
      int selectedValue = selection->selectionValueFromLabel("selected");
      selection->modifySelection(selected,
        "proximity feature",
        selectedValue,
        smtk::view::SelectionAction::UNFILTERED_REPLACE,
        /* bitwise */ true,
        /* notify */ false);
    }
    else
    {
      auto face = resource->addFace();
      face.setName("selected by normal");
      smtk::model::Face(std::dynamic_pointer_cast<smtk::model::Entity>(assoc))
        .owningModel()
        .addCell(face);
      auto fcomp = face.entityRecord();
      session->addStorage(fcomp->id(), geom);
      created->appendValue(fcomp);
      geomMarker.markModified(fcomp);
    }
  }

  result->findInt("outcome")->setValue(static_cast<int>(ProximityFeature::Outcome::SUCCEEDED));
  return result;
}

const char* ProximityFeature::xmlDescription() const
{
  return ProximityFeature_xml;
}

}
}
}
