//=========================================================================
//  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/vtk/vtkGlobalIdBooleans.h"

#include "vtkAppendFilter.h"
#include "vtkArrayDispatch.h"
#include "vtkAssume.h"
#include "vtkCellData.h"
#include "vtkCompositeDataSet.h"
#include "vtkDataArray.h"
#include "vtkDataArrayAccessor.h"
#include "vtkDataSet.h"
#include "vtkInformation.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkThreshold.h"
#include "vtkUnsignedCharArray.h"

#include <algorithm>
#include <set>

namespace // anonymous
{

struct SelectionValueWorker
{
private:
  vtkNew<vtkUnsignedCharArray> m_SelectionValues;
  std::set<vtkIdType> m_toolIds;
  int m_operation;

public:
  SelectionValueWorker(int op)
    : m_operation(op)
  {
    m_SelectionValues->SetName("SelectionValue");
  }

  vtkUnsignedCharArray* SelectionValues() { return m_SelectionValues; }

  template<typename ArrayTypeW, typename ArrayTypeT>
  void operator()(ArrayTypeW* workpieceIdArray, ArrayTypeT* toolIdArray)
  {
    VTK_ASSUME(toolIdArray->GetNumberOfComponents() == 1);
    VTK_ASSUME(workpieceIdArray->GetNumberOfComponents() == 1);

    vtkDataArrayAccessor<ArrayTypeW> ww(workpieceIdArray);
    vtkDataArrayAccessor<ArrayTypeT> tt(toolIdArray);
    m_SelectionValues->SetNumberOfTuples(workpieceIdArray->GetNumberOfTuples());
    vtkIdType nn = toolIdArray->GetNumberOfTuples();
    for (vtkIdType ii = 0; ii < nn; ++ii)
    {
      m_toolIds.insert(tt.Get(ii, 0));
    }
    nn = workpieceIdArray->GetNumberOfTuples();
    if (m_operation == vtkGlobalIdBooleans::DIFFERENCE)
    {
      for (vtkIdType ii = 0; ii < nn; ++ii)
      {
        m_SelectionValues->SetValue(ii, (m_toolIds.find(ww.Get(ii, 0)) == m_toolIds.end()) ? 1 : 0);
      }
    }
    else if (m_operation == vtkGlobalIdBooleans::INTERSECTION)
    {
      for (vtkIdType ii = 0; ii < nn; ++ii)
      {
        m_SelectionValues->SetValue(ii, (m_toolIds.find(ww.Get(ii, 0)) == m_toolIds.end()) ? 0 : 1);
      }
    }
    else
    {
      m_SelectionValues->FillComponent(0, 0);
      vtkGenericWarningMacro("Unknown operation " << m_operation << ".");
    }
  }
};

} // anonymous namespace

vtkStandardNewMacro(vtkGlobalIdBooleans);

vtkGlobalIdBooleans::vtkGlobalIdBooleans()
  : Operation(UNION)
{
  this->SetNumberOfInputPorts(2);
}

vtkGlobalIdBooleans::~vtkGlobalIdBooleans() = default;

void vtkGlobalIdBooleans::PrintSelf(std::ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "Operation: " << this->Operation << "\n";
}

int vtkGlobalIdBooleans::FilterById(vtkDataSet* workpiece, vtkDataSet* tool, vtkDataSet* result)
{
  vtkDataArray* wgid = workpiece->GetCellData()->GetGlobalIds();
  vtkDataArray* tgid = tool->GetCellData()->GetGlobalIds();
  if (!wgid || !tgid)
  {
    vtkErrorMacro("Missing global ID array on workpiece or tool.");
    return 0;
  }
  using Dispatcher = vtkArrayDispatch::Dispatch2ByValueType<vtkArrayDispatch::Integrals,
    vtkArrayDispatch::Integrals>;
  SelectionValueWorker worker(this->Operation);
  if (!Dispatcher::Execute(wgid, tgid, worker))
  {
    worker(wgid, tgid);
  }
  workpiece->GetCellData()->AddArray(worker.SelectionValues());
  vtkNew<vtkThreshold> threshold;
  threshold->SetInputDataObject(0, workpiece);
  threshold->SetInputArrayToProcess(
    0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_CELLS, worker.SelectionValues()->GetName());
  threshold->ThresholdBetween(1, 255); // Anything non-zero
  threshold->Update();
  result->ShallowCopy(threshold->GetOutputDataObject(0));
  result->GetCellData()->RemoveArray(worker.SelectionValues()->GetName());
  return 1;
}

int vtkGlobalIdBooleans::FillInputPortInformation(int /*port*/, vtkInformation* info)
{
  info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataSet");
  // info->Set(vtkAlgorithm::INPUT_IS_REPEATABLE(), 1);
  return 1;
}

int vtkGlobalIdBooleans::RequestData(vtkInformation* /*request*/,
  vtkInformationVector** inInfo,
  vtkInformationVector* outInfo)
{
  auto* workpiece = vtkDataSet::GetData(inInfo[0], 0);
  auto* tool = vtkDataSet::GetData(inInfo[1], 0);
  if (!workpiece || !tool)
  {
    vtkErrorMacro("Missing workpiece or tool.");
    return 0;
  }
  auto* result = vtkDataSet::GetData(outInfo, 0);
  if (!result)
  {
    vtkErrorMacro("No output data object.");
    return 0;
  }
  if (this->Operation == DIFFERENCE || this->Operation == INTERSECTION)
  {
    return this->FilterById(workpiece, tool, result);
  }
  // this->Operation == UNION
  {
    vtkNew<vtkAppendFilter> append;
    append->AddInputData(workpiece);
    append->AddInputData(tool);
    append->MergePointsOn();
    append->Update();
    result->ShallowCopy(append->GetOutputDataObject(0));
    if (!result->GetCellData()->GetGlobalIds() && !result->GetPointData()->GetGlobalIds())
    {
      vtkErrorMacro("No global IDs present.");
      return 0;
    }
  }
  return 1;
}
