<?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\ViisonShippingCommon\Classes;

use Enlight\Event\SubscriberInterface;

/**
 * This class provides the Event Subscriber functionality that is present in the Enlight_Event_EventManager in
 * Shopware starting with version 4.2. By using this class, we are able to use the same functionality also in
 * earlier Shopware versions.
 * TODO remove this class as soon as we do not support Shopware versions < 4.2 anymore
 */
class EventManagerCompat
{

    /**
     * @param SubscriberInterface $subscriber
     */
    public static function addSubscriber(SubscriberInterface $subscriber)
    {
        foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
            if (is_string($params)) {
                self::addListener($eventName, array($subscriber, $params));
            } elseif (is_string($params[0])) {
                self::addListener($eventName, array($subscriber, $params[0]), isset($params[1]) ? $params[1] : 0);
            } else {
                foreach ($params as $listener) {
                    self::addListener($eventName, array($subscriber, $listener[0]), isset($listener[1]) ? $listener[1] : 0);
                }
            }
        }
    }

    /**
     * @param $eventName
     * @param $listener
     * @param int $priority
     *
     * @return  Enlight_Event_EventManager
     */
    private static function addListener($eventName, $listener, $priority = 0)
    {
        $eventManager = Shopware()->Events();

        if ($priority === 0) {
            $priority = null;
        }

        $handler = new \Enlight_Event_Handler_Default(
            $eventName,
            $listener,
            $priority
        );

        $eventManager->registerListener($handler);

        return $eventManager;
    }
}
