//=========================================================================
//  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/Import.h"
#include "smtk/session/aeva/operators/ProximityFeature.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/resource/Manager.h"

#include "smtk/operation/Manager.h"

#include <vtkPolyData.h>

namespace
{
std::string dataRoot = AEVA_DATA_DIR;

bool RunOperation(const smtk::session::aeva::ProximityFeature::Ptr& proximitySelection,
  vtkIdType numberOfSelectedCells,
  const smtk::session::aeva::Session::Ptr& session)
{
  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;
  }

  std::cout << NumberOfCells(selectedData) << "\n";
  if (NumberOfCells(selectedData) != numberOfSelectedCells)
  {
    std::cerr << "Face geometry contains an unexpected number of cells "
              << "(" << NumberOfCells(selectedData) << ")\n";
    return false;
  }
  return true;
}

} // namespace

int TestProximitySelection(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;
  }

  // Create the operation
  auto proximitySelection = operationManager->create<smtk::session::aeva::ProximityFeature>();
  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(2.0);

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

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