//=========================================================================
//  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/session/aeva/CellSelection.h"
#include "smtk/session/aeva/Predicates.h"
#include "smtk/session/aeva/Registrar.h"
#include "smtk/session/aeva/Resource.h"
#include "smtk/session/aeva/Session.h"

#include "smtk/session/aeva/operators/AllPrimitivesFeature.h"
#include "smtk/session/aeva/operators/Import.h"
#include "smtk/session/aeva/operators/PointProximityFeature.h"

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

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

#include "smtk/resource/Manager.h"

#include "smtk/operation/Manager.h"

#include "vtkPolyData.h"

// #include "vtkPolyDataWriter.h"
// #include "vtkNew.h"

namespace
{
std::string dataRoot = AEVA_DATA_DIR;

bool RunOperation(const smtk::session::aeva::PointProximityFeature::Ptr& proximitySelection,
  vtkIdType numberOfSelectedCells,
  vtkIdType numberOfConnectedCells,
  const smtk::session::aeva::Session::Ptr& session)
{
  using smtk::session::aeva::EstimateParametricDimension;
  using smtk::session::aeva::NumberOfCells;

  // Test the ability to operate
  if (!proximitySelection->ableToOperate())
  {
    std::cerr << "proximity selection operation unable to operate.\n";
    return false;
  }

  // Execute the operation
  smtk::operation::Operation::Result proximityResult = proximitySelection->operate();

  // Test for success
  if (proximityResult->findInt("outcome")->value() !=
    static_cast<int>(smtk::operation::Operation::Outcome::SUCCEEDED))
  {
    std::cerr << "Proximity selection operation failed.\n";
    return false;
  }

  // Retrieve the modified selection
  auto componentItem = proximityResult->findComponent("created");

  // Access the generated model
  auto proximal = std::dynamic_pointer_cast<smtk::model::Entity>(componentItem->value());

  // Test model validity
  if (!proximal)
  {
    std::cerr << "Proximity selection result is invalid.\n";
    return false;
  }

  vtkSmartPointer<vtkDataObject> selectedData;
  selectedData = session->findStorage(proximal->id());
  if (!selectedData)
  {
    std::cerr << "No geometry for face.\n";
    return false;
  }

  int dd = EstimateParametricDimension(selectedData);
  vtkIdType nn = NumberOfCells(selectedData);
  std::cout << nn << " cells, dimension " << dd << "\n";
  if (nn != numberOfSelectedCells)
  {
    std::cerr << "Selected geometry contains an unexpected number of vertices "
              << "(" << nn << ").\n";
    return false;
  }
  if (dd != 0)
  {
    std::cerr << "Selected geometry has unexpected dimension " << dd << ".\n";
    return false;
  }

  auto nodesToCells = smtk::session::aeva::AllPrimitivesFeature::create();
  nodesToCells->parameters()->associations()->appendValue(proximal);
  auto connectedPrimitivesResult = nodesToCells->operate();
  if (connectedPrimitivesResult->findInt("outcome")->value() !=
    static_cast<int>(smtk::operation::Operation::Outcome::SUCCEEDED))
  {
    std::cerr << "All-primitives selection operation failed.\n";
    return false;
  }

  // Retrieve the modified selection
  auto connectedItem = connectedPrimitivesResult->findComponent("created");

  // Access the generated model
  auto connected = std::dynamic_pointer_cast<smtk::model::Entity>(connectedItem->value());
  std::cout << "  connected selections " << connectedItem->numberOfValues() << "\n";
  selectedData = session->findStorage(connected->id());
  if (!selectedData)
  {
    std::cerr << "No geometry for connected primitives.\n";
    return false;
  }
  dd = EstimateParametricDimension(selectedData);
  nn = NumberOfCells(selectedData);
  std::cout << "  " << nn << " cells connected, dimension " << dd << "\n";
  if (dd != 2)
  {
    std::cerr << "  Unexpected connected-cell dimension " << dd << ".\n";
    return false;
  }
#if 0
  // Do not test this yet as sometimes the boundary surface of volume
  // elements is returned (depending on which primary geometry has the
  // lower UUID – which varies each run).
  if (nn != numberOfConnectedCells)
  {
    std::cerr << "  Unexpected number of connected cells " << nn << ".\n";
    vtkNew<vtkPolyDataWriter> wri;
    wri->SetFileName("/tmp/ucn.vtk");
    wri->SetInputDataObject(0, selectedData);
    wri->Write();
    return false;
  }
#else
  (void)numberOfConnectedCells;
#endif

  return true;
}

} // namespace

int TestPointProximitySelection(int argc, char* argv[])
{
  (void)argc;
  (void)argv;

  // Create a resource manager
  smtk::resource::Manager::Ptr resourceManager = smtk::resource::Manager::create();

  // Register the aeva session to the resource manager
  {
    smtk::session::aeva::Registrar::registerTo(resourceManager);
  }

  // Create an operation manager
  smtk::operation::Manager::Ptr operationManager = smtk::operation::Manager::create();

  // Register the aeva session to the operation manager
  {
    smtk::session::aeva::Registrar::registerTo(operationManager);
  }

  // Register the resource manager to the operation manager (newly created
  // resources will be automatically registered to the resource manager).
  operationManager->registerResourceManager(resourceManager);
  smtk::session::aeva::Session::Ptr session = smtk::session::aeva::Session::create();

  smtk::model::Entity::Ptr model;
  std::string testFiles[] = { "/med/oks003_FMB_AGS_LVTIT.med", "/med/oks003_ACL_AGS_LVTIT.med" };
  auto rsrc = resourceManager->create<smtk::session::aeva::Resource>();
  rsrc->setSession(session);

  for (auto& testFile : testFiles)
  {
    // Create an import operation
    smtk::session::aeva::Import::Ptr importOp =
      operationManager->create<smtk::session::aeva::Import>();
    if (!importOp)
    {
      std::cerr << "No import operation\n";
      return 1;
    }

    // Set the file path
    std::string importFilePath(dataRoot);
    importFilePath += testFile;
    importOp->parameters()->findFile("filename")->setValue(importFilePath);
    importOp->parameters()->associate(rsrc);

    // Test the ability to operate
    if (!importOp->ableToOperate())
    {
      std::cerr << "Import operation unable to operate\n";
      return 1;
    }

    // Execute the operation
    smtk::operation::Operation::Result importOpResult = importOp->operate();

    // Test for success
    if (importOpResult->findInt("outcome")->value() !=
      static_cast<int>(smtk::operation::Operation::Outcome::SUCCEEDED))
    {
      std::cerr << "Import operation failed\n";
      return 1;
    }
  }

  // Access all of the model's faces
  smtk::model::EntityRefs faces =
    rsrc->entitiesMatchingFlagsAs<smtk::model::EntityRefs>(smtk::model::FACE);
  if (faces.empty())
  {
    std::cerr << "No faces\n";
    return 1;
  }

  smtk::model::Face aclFace;
  smtk::model::Face fmbFace;
  for (const auto& face : faces)
  {
    if (face.name() == "ACL surface 0")
    {
      aclFace = face;
    }
    else if (face.name() == "FMB surface 0")
    {
      fmbFace = face;
    }
    std::cout << "Face " << face.name() << "\n";
  }
  if (!aclFace.isValid() || !fmbFace.isValid())
  {
    std::cerr << "Did not find input faces.\n";
    return 1;
  }

  smtk::model::EntityRefs volumes =
    rsrc->entitiesMatchingFlagsAs<smtk::model::EntityRefs>(smtk::model::VOLUME);
  if (volumes.empty())
  {
    std::cerr << "No volumes.\n";
    return 1;
  }

  smtk::model::Volume aclVol;
  for (const auto& volume : volumes)
  {
    if (volume.name() == "ACL volume 0")
    {
      aclVol = volume;
    }
  }
  if (!aclVol.isValid())
  {
    std::cerr << "Did not find input volume.\n";
    return 1;
  }

  // Create the operation
  auto proximitySelection = operationManager->create<smtk::session::aeva::PointProximityFeature>();
  if (!proximitySelection)
  {
    std::cerr << "No proximity selection operation\n";
    return 1;
  }

  // Set the input face
  proximitySelection->parameters()->associate(aclFace.component());
  proximitySelection->parameters()->findComponent("target")->setValue(fmbFace.component());
  proximitySelection->parameters()->findDouble("distance")->setValue(1.0);

  // Set the angle tolerance (but don't enable yet)
  proximitySelection->parameters()->findDouble("angle")->setValue(45.);

  if (!RunOperation(proximitySelection, 1658, 4552, session))
  {
    return 1;
  }

  proximitySelection->parameters()->findDouble("angle")->setIsEnabled(true);
  if (!RunOperation(proximitySelection, 1095, 4146, session))
  {
    return 1;
  }

  proximitySelection->parameters()->associations()->setValue(0, aclVol.component());
  proximitySelection->parameters()->findDouble("angle")->setIsEnabled(false);
  proximitySelection->parameters()->findDouble("distance")->setValue(1.5);
  if (!RunOperation(proximitySelection, 3169, 6974, session))
  {
    return 1;
  }

  return 0;
}
