//=========================================================================
//  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 "vtk/aeva/ext/vtkGlobalIdBooleans.h"
#include "vtk/aeva/ext/vtkAppendFilterIntIds.h"

#include "vtkArrayDispatch.h"
#include "vtkAssume.h"
#include "vtkCellData.h"
#include "vtkCellTypes.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)
{
  int wdim =
    workpiece->GetNumberOfCells() > 0 ? (workpiece->GetCellType(0) == VTK_VERTEX ? 0 : 2) : -1;
  int tdim = tool->GetNumberOfCells() > 0 ? (tool->GetCellType(0) == VTK_VERTEX ? 0 : 2) : -1;
  int attribType;
  if (wdim == 0 && tdim == 0)
  {
    attribType = vtkDataObject::POINT;
  }
  else if (wdim > 0 && tdim > 0)
  {
    attribType = vtkDataObject::CELL;
  }
  else
  {
    vtkErrorMacro(
      "Workpiece (" << wdim << ") and tool (" << tdim << ") dimensions mismatch or are unknown.");
    return 0;
  }
  vtkDataSetAttributes* workAttrib = workpiece->GetAttributes(attribType);
  vtkDataSetAttributes* toolAttrib = tool->GetAttributes(attribType);
  vtkDataArray* wgid = workAttrib->GetGlobalIds();
  vtkDataArray* tgid = toolAttrib->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);
  }
  workAttrib->AddArray(worker.SelectionValues());
  vtkNew<vtkThreshold> threshold;
  threshold->SetInputDataObject(0, workpiece);
  threshold->SetInputArrayToProcess(0,
    0,
    0,
    attribType == vtkDataObject::CELL ? vtkDataObject::FIELD_ASSOCIATION_CELLS
                                      : vtkDataObject::FIELD_ASSOCIATION_POINTS,
    worker.SelectionValues()->GetName());
  threshold->ThresholdBetween(1, 255); // Anything non-zero
  threshold->Update();
  result->ShallowCopy(threshold->GetOutputDataObject(0));
  result->GetAttributes(attribType)->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
  {
    // TODO: Handle unions of node sets.
    vtkNew<vtkAppendFilterIntIds> 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;
}
