#include <vtkAdjacentVertexIterator.h>
#include <vtkDataSetAttributes.h>
#include <vtkGraphLayoutView.h>
#include <vtkLookupTable.h>
#include <vtkMutableDirectedGraph.h>
#include <vtkNamedColors.h>
#include <vtkNew.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkTree.h>
#include <vtkUnsignedCharArray.h>
#include <vtkViewTheme.h>

// For compatibility with new VTK generic data arrays.
#ifdef vtkGenericDataArray_h
#define InsertNextTupleValue InsertNextTypedTuple
#endif

int main(int, char*[])
{
  vtkNew<vtkNamedColors> colors;

  vtkNew<vtkMutableDirectedGraph> g;

  // Create 4 vertices.
  vtkIdType v0 = g->AddVertex();
  vtkIdType v1 = g->AddVertex();
  vtkIdType v2 = g->AddVertex();
  vtkIdType v3 = g->AddVertex();

  // Add the edges.
  g->AddEdge(v0, v1);
  g->AddEdge(v0, v2);
  g->AddEdge(v2, v3);

  vtkNew<vtkTree> tree;
  bool success = tree->CheckedShallowCopy(g);
  std::cout << "Is it a tree? " << std::boolalpha << success << std::endl;

  // Create the color array.
  vtkNew<vtkUnsignedCharArray> vertexColors;
  vertexColors->SetNumberOfComponents(1);
  vertexColors->SetName("Color");

  vtkNew<vtkLookupTable> lookupTable;
  lookupTable->SetNumberOfTableValues(3);
  // Origin
  lookupTable->SetTableValue(0, colors->GetColor4d("Red").GetData());
  // Unconnected vertices
  lookupTable->SetTableValue(1, colors->GetColor4d("Blue").GetData());
  // Connected vertices
  lookupTable->SetTableValue(2, colors->GetColor4d("Green").GetData());
  lookupTable->Build();

  // Setup the colors.
  vertexColors->InsertNextValue(0);
  vertexColors->InsertNextValue(1);
  // vertexColors->InsertNextValue(2);
  // vertexColors->InsertNextValue(3);

  vtkNew<vtkAdjacentVertexIterator> iterator;
  tree->GetAdjacentVertices(0, iterator);

  auto i = 2;
  while (iterator->HasNext())
  {
    vtkIdType nextVertex = iterator->Next();
    std::cout << "Next adjacent vertex: " << nextVertex << std::endl;
    vertexColors->InsertNextValue(i);
    ++i;
  }

  // Add the color array to the graph.
  tree->GetVertexData()->AddArray(vertexColors);

  vtkNew<vtkGraphLayoutView> graphLayoutView;
  graphLayoutView->AddRepresentationFromInput(tree);
  graphLayoutView->SetLayoutStrategyToTree();
  graphLayoutView->SetVertexColorArrayName("Color");
  graphLayoutView->ColorVerticesOn();

  vtkNew<vtkViewTheme> theme;
  theme->SetPointLookupTable(lookupTable);
  theme->ScalePointLookupTableOff();
  graphLayoutView->ApplyViewTheme(theme);

  graphLayoutView->ResetCamera();
  graphLayoutView->GetInteractor()->Initialize();
  graphLayoutView->GetInteractor()->Start();

  return EXIT_SUCCESS;
}
