<?php

class Waindigo_ResMans_Listener_TemplateModification extends Waindigo_Listener_TemplateModification
{

    const SIMPLE_CACHE_KEY = 'waindigo_resMans_resourceManagers';

    protected $_phrasesCache = array();

    public static function resourceIndex(array $matches)
    {
        $modification = new Waindigo_ResMans_Listener_TemplateModification($matches[0]);

        return $modification->_resourceIndex();
    } /* END resourceIndex */

    public static function resourcesTabLinks(array $matches)
    {
        $modification = new Waindigo_ResMans_Listener_TemplateModification($matches[0]);

        return $modification->_resourcesTabLinks();
    } /* END resourcesTabLinks */

    protected function _resourcesTabLinks()
    {
        $resourceManagers = XenForo_Application::getSimpleCacheData(self::SIMPLE_CACHE_KEY);

        if ($resourceManagers) {
            $originalContents = $this->_contents;

            $originalContents = $this->_replaceActiveAuthorLink($originalContents);

            $standardContents = $this->_replacePhrases($originalContents, 0);
            $newContents = $this->_replaceLinks($standardContents, 'resources');

            $this->_contents = '<xen:if is="!{$resourceManager}">' . $newContents;

            $count = 0;
            foreach ($resourceManagers as $resourceManagerId => $resourceManager) {
                $this->_contents .= '<xen:elseif is="{$resourceManager.resource_manager_id} == ' . $resourceManagerId .
                     '" />';
                if ($resourceManager['language_id']) {
                    $newContents = $this->_replacePhrases($originalContents, $resourceManager['language_id']);
                    $newContents = $this->_replaceLinks($newContents, $resourceManager['original_prefix']);
                } else {
                    $newContents = $this->_replaceLinks($standardContents, $resourceManager['original_prefix']);
                }
                $this->_contents .= $newContents;
                $count++;
            }

            if ($count == 0) {
                $newContents = $originalContents;
                $this->_contents = '<xen:if is="!{$resourceManager}">' . $newContents;
            }

            $this->_contents .= '</xen:if>';
        }

        return $this->_contents;
    } /* END _resourcesTabLinks */

    protected function _replaceActiveAuthorLink($contents)
    {
        $pattern = '<li><a href="{xen:link resources/authors}">{xen:phrase most_active_authors}</a></li>';
        $replacement = '<xen:if is="{$showActiveAuthorLink}">' . $pattern . '</xen:if>';
        return str_replace($pattern, $replacement, $contents);
    } /* END _replaceActiveAuthorLink */

    protected function _replacePhrases($contents, $languageId)
    {
        $replacements = array();
        $phraseTitles = array();

        preg_match_all('#\{xen:phrase ("|\'|)([a-z0-9-_]+)\\1(,\s*("|\')(.+)\\4)*\}#iU', $contents, $matches,
            PREG_SET_ORDER);
        foreach ($matches as $match) {
            $phraseTitles[$match[2]] = $match[0];
        }

        $db = XenForo_Application::getDb();

        if (!isset($this->_phrasesCache[$languageId])) {
            $this->_phrasesCache[$languageId] = $db->fetchPairs(
                '
        			SELECT title, phrase_text
        			FROM xf_phrase_compiled
        			WHERE language_id = ?
        				AND title IN (' . $db->quote(array_keys($phraseTitles)) . ')
        		', $languageId);
        }
        $phrases = $this->_phrasesCache[$languageId];

        foreach ($phrases as $title => $phraseText) {
            $replacements[$phraseTitles[$title]] = $phraseText;
        }

        if ($replacements) {
            foreach ($replacements as $search => $replace) {
                $contents = str_replace($search, (string) $replace, $contents);
            }
        }

        return $contents;
    } /* END _replacePhrases */

    protected function _replaceLinks($contents, $originalPrefix)
    {
        $linkReplacements = array();

        preg_match_all('#\{xen:link ("|\'|)resources(.*)\}#iU', $contents, $matches, PREG_SET_ORDER);
        foreach ($matches as $match) {
            $linkReplacements[$match[0]] = '{xen:helper resourcelink, ' . $match[1] . $originalPrefix . $match[2] . '}';
        }

        if ($linkReplacements) {
            foreach ($linkReplacements as $search => $replace) {
                $contents = str_replace($search, (string) $replace, $contents);
            }
        }

        return $contents;
    } /* END _replaceLinks */

    protected function _resourceIndex()
    {
        $pattern = "#(<li class=\"{xen:if '{\\\$order} == \"([A-z_{}\$]+)\"'.*order=)[A-z_{}\$]*('.*</li>)#Us";
        $replacement = "<xen:if is=\"(!{\$hideTabs} || !in_array('\${2}', {\$hideTabs})) && {\$defaultTab} != '\${2}'\">\${1}\${2}\${3}</xen:if>";

        $this->_patternReplace($pattern, $replacement, $this->_contents, -1);

        $codeSnippet = "<ol class=\"tabs\">";
        $viewParams = $this->_fetchViewParams();
        $rendered = "<xen:if is=\"{\$defaultTab}\"><li class=\"{xen:if '{\$order} == \"{\$defaultTab}\"', active}\"><a href=\"{xen:if \$category, {xen:link resources/categories, \$category, '_params={\$pageNavParams}', 'order='}, {xen:link resources, '', '_params={\$pageNavParams}', 'order='}}\">{\$defaultTabLabel}</a></li></xen:if>";
        $this->_appendAtCodeSnippet($codeSnippet, $rendered);

        return $this->_contents;
    } /* END _resourceIndex */
}