<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

namespace Shopware\Plugins\ViisonPickwareCommon\Components;

use Shopware\Components\DependencyInjection\Container;
use Shopware\Components\DependencyInjection\ContainerAwareInterface;

class PickwareResourceManager
{
    /**
     * The name of the event, which is fired to find a Pickware resource by name.
     */
    const EVENT_FIND_PICKWARE_RESOURCE = 'Shopware_Plugins_ViisonPickware_FindPickwareResource';

    /**
     * @var \Enlight_Event_EventManager $eventManager;
     */
    private $eventManager;

    /**
     * @var \Shopware\Components\DependencyInjection\Container $container
     */
    private $container;

    /**
     * @param \Shopware\Components\DependencyInjection\Container $container
     */
    public function __construct(Container $container)
    {
        $this->eventManager = $container->get('events');
        $this->container = $container;
    }

    /**
     * Tries to find the requested resource by firing the 'Shopware_Plugins_ViisonPickware_FindPickwareResource'
     * event. If the resource was found, it is initialized with the DI container and returned.
     *
     * @param $name
     * @return mixed
     * @throws \Exception If the resource with the given name could not be found.
     */
    public function getResource($name)
    {
        // Try to find the resource
        $resourceClass = $this->eventManager->notifyUntil(
            static::EVENT_FIND_PICKWARE_RESOURCE,
            [
                'resourceName' => ucfirst($name),
            ]
        );
        if (!$resourceClass || !$resourceClass->getReturn()) {
            throw new \Exception(sprintf('The Pickware resource "%s" could not be found.', $name));
        }

        // Load resource
        $resourceClass = $resourceClass->getReturn();
        $resource = new $resourceClass();
        if ($resource instanceof ContainerAwareInterface) {
            $resource->setContainer($this->container);
        }

        return $resource;
    }
}
