<?php

/**
 *
 * @see XenResource_Route_Prefix_Resources
 */
class Waindigo_ResMans_Extend_XenResource_Route_Prefix_Resources extends XFCP_Waindigo_ResMans_Extend_XenResource_Route_Prefix_Resources
{

    const SIMPLE_CACHE_KEY = 'waindigo_resMans_resourceManagers';

    /**
     *
     * @see XenResource_Route_Prefix_Resources::match()
     */
    public function match($routePath, Zend_Controller_Request_Http $request, XenForo_Router $router)
    {
        /* @var $routeMatch XenForo_RouteMatch */
        $routeMatch = parent::match($routePath, $request, $router);

        $resourceManager = Waindigo_ResMans_ResourceManager::getInstance();

        $majorSection = $resourceManager->get('original_prefix');

        if ($majorSection) {
            $routeMatch->setSections($majorSection);
        }

        return $routeMatch;
    } /* END match */

    /**
     *
     * @see XenResource_Route_Prefix_Resources::buildLink()
     */
    public function buildLink($originalPrefix, $outputPrefix, $action, $extension, $data, array &$extraParams)
    {
        if (!empty($data['resource_manager_id_waindigo'])) {
            $resourceManagers = XenForo_Application::getSimpleCacheData(self::SIMPLE_CACHE_KEY);
            if (isset($resourceManagers[$data['resource_manager_id_waindigo']])) {
                $resourceManager = $resourceManagers[$data['resource_manager_id_waindigo']];
                $outputPrefix = $resourceManager['original_prefix'];
            }
        } else {
            $resourceManager = Waindigo_ResMans_ResourceManager::getInstance();

            if (empty($data['forcePrefix'])) {
                if (Waindigo_ResMans_ResourceManager::getAlternativeOriginalPrefix()) {
                    $outputPrefix = Waindigo_ResMans_ResourceManager::getAlternativeOriginalPrefix();
                } elseif (!empty($resourceManager['original_prefix'])) {
                    $outputPrefix = $resourceManager['original_prefix'];
                }
            }
        }

        $xenOptions = XenForo_Application::getOptions();
        if (!$xenOptions->waindigo_resMans_showResourcesTab && $outputPrefix == 'resources') {
            return false;
        }

        $originalPrefix = $outputPrefix;

        $link = parent::buildLink($originalPrefix, $outputPrefix, $action, $extension, $data, $extraParams);

        if (!$link) {
            $link = $outputPrefix . '/' . $action;
        }

        return $link;
    } /* END buildLink */
}