<?php

namespace AutoAdmin\Bundle\Content\Hierarchy\Helper;

use AutoAdmin\Bundle\Content\Hierarchy\Exception\LoopingHierarchy;
use AutoAdmin\Bundle\Content\Hierarchy\Model\Interfaces\SelfHierarchyInterface;

class SelfHierarchyHelper
{
    /**
     * @throws LoopingHierarchy
     */
    public function ensureNoLoop(SelfHierarchyInterface $content, $buffer = [])
    {
        if (in_array($content, $buffer)) {
            throw new LoopingHierarchy($content);
        }
        $buffer[] = $content;

        $parent = $this->ensureNoLoop($content->getParent(), $buffer);

        if (in_array($parent, $buffer)) {
            throw new LoopingHierarchy($content);
        }
        $buffer[] = $parent;

        return $buffer;
    }
    public function isLooping(SelfHierarchyInterface $content, $buffer = []): bool
    {
        try {
            $this->ensureNoLoop($content);
        } catch (LoopingHierarchy $e) {
            return true;
        }

        return false;
    }

    public function flattenHierarchy(SelfHierarchyInterface $childSubject)
    {
        $flat = $this->ensureNoLoop($childSubject);
        $descending = array_reverse($flat);

        return $descending;
    }
}
