# Copyright 1999-2016. Parallels IP Holdings GmbH. All Rights Reserved.
package LegacyPanel::Tree::Builder;

use strict;
use warnings;

use Carp;

use Tree::Simple;

# silence the warning related to recursion and prototypes,
# see http://www.perlmonks.org/?node_id=833753
sub _buildSubtreeRecurse($$);

sub buildTree($) {
  my ($entityFactory) = @_;

  my $tree = Tree::Simple->new("root", Tree::Simple->ROOT);;

  # admin
  {
    my $admin = $entityFactory->get('admin');
    $tree->addChild(_buildSubtreeRecurse($entityFactory, $admin));
  }

  # resellers
  {
    my @ids = $entityFactory->getAllEntityIdList('reseller');
    foreach my $id (@ids) {
      my $reseller = $entityFactory->get('reseller', $id);
      $tree->addChild(_buildSubtreeRecurse($entityFactory, $reseller));
    }
  }

  return $tree;
}

sub _buildSubtreeRecurse($$) {
  my ($entityFactory, $entity) = @_;
  confess() if !defined($entity);

  my $treeNode = Tree::Simple->new($entity);
  my $childType = $entity->getChildType();
  if (defined($childType)) {
    my @childrenId = $entity->getChildrenIdList();
    foreach my $childId (@childrenId) {
      my $childEntity = $entityFactory->get($childType, $childId);
      $treeNode->addChild(_buildSubtreeRecurse($entityFactory, $childEntity));
    }
  }
  return $treeNode;
}

1;
