<?php

declare(strict_types=1);

namespace Laminas\View\Resolver;

use Countable;
use IteratorAggregate;
use Laminas\Stdlib\PriorityQueue;
use Laminas\View\Renderer\RendererInterface as Renderer;
use Laminas\View\Resolver\ResolverInterface as Resolver;
use ReturnTypeWillChange; // phpcs:ignore

use function count;

class AggregateResolver implements Countable, IteratorAggregate, Resolver
{
    public const FAILURE_NO_RESOLVERS = 'AggregateResolver_Failure_No_Resolvers';
    public const FAILURE_NOT_FOUND    = 'AggregateResolver_Failure_Not_Found';

    /**
     * Last lookup failure
     *
     * @var false|string
     */
    protected $lastLookupFailure = false;

    /** @var Resolver */
    protected $lastSuccessfulResolver;

    /** @var PriorityQueue */
    protected $queue;

    /**
     * Constructor
     *
     * Instantiate the internal priority queue
     */
    public function __construct()
    {
        $this->queue = new PriorityQueue();
    }

    /**
     * Return count of attached resolvers
     *
     * @return int
     */
    #[ReturnTypeWillChange]
    public function count()
    {
        return $this->queue->count();
    }

    /**
     * IteratorAggregate: return internal iterator
     *
     * @return PriorityQueue
     */
    #[ReturnTypeWillChange]
    public function getIterator()
    {
        return $this->queue;
    }

    /**
     * Attach a resolver
     *
     * @param  int $priority
     * @return AggregateResolver
     */
    public function attach(Resolver $resolver, $priority = 1)
    {
        $this->queue->insert($resolver, $priority);
        return $this;
    }

    /**
     * Resolve a template/pattern name to a resource the renderer can consume
     *
     * @param  string $name
     * @return false|string
     */
    public function resolve($name, ?Renderer $renderer = null)
    {
        $this->lastLookupFailure      = false;
        $this->lastSuccessfulResolver = null;

        if (0 === count($this->queue)) {
            $this->lastLookupFailure = static::FAILURE_NO_RESOLVERS;
            return false;
        }

        foreach ($this->queue as $resolver) {
            $resource = $resolver->resolve($name, $renderer);
            if ($resource) {
                // Resource found; return it
                $this->lastSuccessfulResolver = $resolver;
                return $resource;
            }
        }

        $this->lastLookupFailure = static::FAILURE_NOT_FOUND;
        return false;
    }

    /**
     * Return the last successful resolver, if any
     *
     * @return Resolver
     */
    public function getLastSuccessfulResolver()
    {
        return $this->lastSuccessfulResolver;
    }

    /**
     * Get last lookup failure
     *
     * @return false|string
     */
    public function getLastLookupFailure()
    {
        return $this->lastLookupFailure;
    }
}
