<?php

namespace Comitium5\DesignerBundle\Resolver\Template;

use Comitium5\DesignerBundle\Entity\Template;

/**
 * Class TemplateTreeResolver
 *
 * Joan Pont <joan.pont@bab-soft.com>
 * @package Comitium5\DesignerBundle\Resolver\Template
 */
class TemplateTreeResolver
{
    /**
     * @param $templates
     * @param null $parent
     *
     * @return array
     */
    public static function resolve(&$templates, $parent = null) : array
    {
        $children = [];
        $parentId = null;

        if (!empty($parent)) {
            $parentId = $parent->getId();
        }

        foreach ($templates as $template) {
            /** @var $template Template */
            $templateParentId = empty($template->getParent()) ? null : $template->getParent()->getId();

            if ($templateParentId == $parentId) {
                $childTemplates = self::resolve($templates, $template);

                foreach ($childTemplates as $childTemplate) {
                    $template->addChild($childTemplate);
                }

                $children[] = $template;
            }
        }

        return $children;
    }
}