//=========================================================================
//  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/GrowSelection.h"
#include "smtk/session/aeva/operators/Import.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;
}

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

  using smtk::session::aeva::NumberOfCells;

  // 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[] = { "/vtk/oks003_TBB_AGS.vtk", "/vtk/mesh_MAT.vtk" };
  vtkIdType counts[][4] = { { 96340, 192676, 94134, 6383 },
    // 10751 cells in the volume, select cell on the surface.
    { 13760, 5888, 11000, 256 } };

  for (int ii = 0; ii < 2; ++ii)
  {
    {
      auto rsrc = resourceManager->create<smtk::session::aeva::Resource>();
      rsrc->setSession(session);
      // 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 += testFiles[ii];
      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();

      // Retrieve the resulting model
      smtk::attribute::ComponentItemPtr componentItem =
        std::dynamic_pointer_cast<smtk::attribute::ComponentItem>(
          importOpResult->findComponent("created"));

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

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

      // Test model validity
      if (!model->referenceAs<smtk::model::Model>().isValid())
      {
        std::cerr << "Imported model is invalid\n";
        return 1;
      }
    }

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

    smtk::model::Face face = *faces.begin();
    std::cout << "First face is " << face.name() << "\n";

    vtkSmartPointer<vtkPolyData> facePD =
      vtkPolyData::SafeDownCast(session->findStorage(face.entity()));

    if (!facePD)
    {
      std::cerr << "No geometry for face\n";
      return 1;
    }

    if (facePD->GetNumberOfPoints() != counts[ii][0] || facePD->GetNumberOfCells() != counts[ii][1])
    {
      std::cerr << "Face geometry contains an unexpected number of points "
                << facePD->GetNumberOfPoints() << " and/or cells " << facePD->GetNumberOfCells()
                << "\n";
      return 1;
    }

    vtkSmartPointer<vtkDataObject> selectedData;
    // Create a cell selection
    auto cellSelection = smtk::session::aeva::CellSelection::create(
      std::dynamic_pointer_cast<smtk::session::aeva::Resource>(face.resource()),
      { counts[ii][2] },
      operationManager);
    std::cout << "cell selection " << NumberOfCells(cellSelection->data()) << "\n";
    // Create an ReconstructSurface operation
    auto growSelection = operationManager->create<smtk::session::aeva::GrowSelection>();
    if (!growSelection)
    {
      std::cerr << "No grow selection operation\n";
      return 1;
    }

    // Set the input face
    growSelection->parameters()->associate(cellSelection);

    // Set the angle tolerance
    growSelection->parameters()->findDouble("angle")->setValue(5.);

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

    // Execute the operation
    smtk::operation::Operation::Result growResult = growSelection->operate();

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

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

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

    // Test model validity
    if (!grown)
    {
      std::cerr << "Grow selection result is invalid\n";
      return 1;
    }

    selectedData = session->findStorage(grown->id());
    if (!selectedData)
    {
      std::cerr << "No geometry for face\n";
      return 1;
    }

    std::cout << NumberOfCells(selectedData) << "\n";
    if (NumberOfCells(selectedData) != counts[ii][3])
    {
      std::cerr << "Face geometry contains an unexpected number of points and/or cells\n";
      return 1;
    }
  }
  return 0;
}
