// SPDX-FileCopyrightText: Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
// SPDX-License-Identifier: BSD-3-Clause
#include "vtkAssemblyPath.h"

#include "vtkAssemblyNode.h"
#include "vtkObjectFactory.h"
#include "vtkProp.h"
#include "vtkTransform.h"

VTK_ABI_NAMESPACE_BEGIN
vtkStandardNewMacro(vtkAssemblyPath);

vtkAssemblyPath::vtkAssemblyPath()
{
  this->Transform = vtkTransform::New();
  this->Transform->PreMultiply();
  this->TransformedProp = nullptr;
}

vtkAssemblyPath::~vtkAssemblyPath()
{
  this->Transform->Delete();
  if (this->TransformedProp != nullptr)
  {
    this->TransformedProp->Delete();
  }
}

void vtkAssemblyPath::AddNode(vtkProp* p, vtkMatrix4x4* m)
{
  vtkAssemblyNode* n = vtkAssemblyNode::New();
  n->SetViewProp(p);
  n->SetMatrix(m); // really a copy because we're gonna compute with it
  this->AddNode(n);
  n->Delete(); // ok reference counted
}

void vtkAssemblyPath::AddNode(vtkAssemblyNode* n)
{
  // First add the node to the list
  this->vtkCollection::AddItem(n);

  // Grab the matrix, if any, and concatenate it
  this->Transform->Push(); // keep in sync with list of nodes
  vtkMatrix4x4* matrix;
  if ((matrix = n->GetMatrix()) != nullptr)
  {
    this->Transform->Concatenate(matrix);
    this->Transform->GetMatrix(matrix); // replace previous matrix
  }
}

vtkAssemblyNode* vtkAssemblyPath::GetNextNode()
{
  return static_cast<vtkAssemblyNode*>(this->GetNextItemAsObject());
}

vtkAssemblyNode* vtkAssemblyPath::GetFirstNode()
{
  return this->Top ? static_cast<vtkAssemblyNode*>(this->Top->Item) : nullptr;
}

vtkAssemblyNode* vtkAssemblyPath::GetLastNode()
{
  return this->Bottom ? static_cast<vtkAssemblyNode*>(this->Bottom->Item) : nullptr;
}

void vtkAssemblyPath::DeleteLastNode()
{
  vtkAssemblyNode* node = this->GetLastNode();
  this->vtkCollection::RemoveItem(node);
  this->Transform->Pop();
}

void vtkAssemblyPath::ShallowCopy(vtkAssemblyPath* path)
{
  this->RemoveAllItems();

  vtkAssemblyNode* node;
  for (path->InitTraversal(); (node = path->GetNextNode());)
  {
    this->vtkCollection::AddItem(node);
  }
}

vtkMTimeType vtkAssemblyPath::GetMTime()
{
  vtkMTimeType mtime = this->vtkCollection::GetMTime();

  vtkAssemblyNode* node;
  for (this->InitTraversal(); (node = this->GetNextNode());)
  {
    vtkMTimeType nodeMTime = node->GetMTime();
    if (nodeMTime > mtime)
    {
      mtime = nodeMTime;
    }
  }
  return mtime;
}

void vtkAssemblyPath::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}
VTK_ABI_NAMESPACE_END
