//=========================================================================
//  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/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/ReconstructSurface.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 TestReconstructSurfaceOp(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::model::Entity::Ptr model;

  {
    // 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 += "/vtk/oks003_TBB_AGS.vtk";
    importOp->parameters()->findFile("filename")->setValue(importFilePath);

    // 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;
    }
  }

  smtk::session::aeva::Session::Ptr session =
    std::static_pointer_cast<smtk::session::aeva::Resource>(model->modelResource())->session();

  // 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();

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

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

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

  {
    // Create an ReconstructSurface operation
    smtk::session::aeva::ReconstructSurface::Ptr reconstructSurface =
      operationManager->create<smtk::session::aeva::ReconstructSurface>();
    if (!reconstructSurface)
    {
      std::cerr << "No reconstruct surface operation\n";
      return 1;
    }

    // Set the input face
    reconstructSurface->parameters()->associate(face.component());

    // Set the voxel grid dimensions
    reconstructSurface->parameters()->findInt("dimensions")->setValue(0, 100);
    reconstructSurface->parameters()->findInt("dimensions")->setValue(1, 100);
    reconstructSurface->parameters()->findInt("dimensions")->setValue(2, 100);

    // Set the radius of influence
    reconstructSurface->parameters()->findDouble("radius")->setValue(5.);

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

    // Execute the operation
    smtk::operation::Operation::Result reconstructSurfaceResult = reconstructSurface->operate();

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

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

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

    // Test model validity
    if (!face.isValid())
    {
      std::cerr << "Reconstructed face is invalid\n";
      return 1;
    }
  }

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

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

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

  return 0;
}
