<?php

namespace CouponsPlus\App\Factory;

use CouponsPlus\App\Factory\Abilities\Overloadable;
use CouponsPlus\App\Factory\Abilities\OverloadableFactory;
use CouponsPlus\Original\Collections\Collection;
use Exception;


class FactoryOverloader implements Overloadable
{
    private $overloadableFactories;

    public function __construct(Collection $overloadableFactories)
    {
        $this->overloadableFactories = $overloadableFactories;
    } 

    public function overload(/*mixed*/ $value) /*: object*/
    {
        return $this->overloadableFactories->find(
            function(OverloadableFactory $overloadableFactory) use ($value) {
                return $overloadableFactory->canCreate(
                    $value
                );
            }
        ) ?? $this->throwExceptionWhenNotFound();
    }

    protected function throwExceptionWhenNotFound() : void
    {
        throw new Exception("No overloadableFactory found!");
    }
}