<?php
/**
 * Href Lang Tags Extension
 *
 * @author Vincent van Waasbergen <v.vanwaasbergen@visualmedia.nl>
 */
namespace VisualM\TagManagerBundle\Twig;

use RuntimeException;
use Twig_Extension;
use Twig_SimpleFunction;

use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;

use VisualM\RoutingBundle\Model\RouteManager;

/**
* Href Lang Tags Extension
*
* @author Vincent van Waasbergen <v.vanwaasbergen@visualmedia.nl>
 */
class HrefLangTagsExtension extends Twig_Extension
{
    /**
     * Extension Name
     * @var string
     */
    const EXTENSION_NAME = 'href_lang_tags';

    /**
     * Route Manager
     * @var RouteManager
     */
    protected $routeManager;

    /**
     * Request
     * @var Request
     */
    protected $request;

    /**
     * Container
     * @var ContainerInterface
     */
    protected $container;

    /**
     * Cache
     * @var Array
     */
    protected $cache;

    /**
     * Constructor
     *
     * @param RouteProvider $routeProvider
     * @param RequestStack $requestStack
     * @param Array $hosts
     */
    function __construct(RouteManager $routeManager, ContainerInterface $container)
    {
        $this->routeManager = $routeManager;
        $this->container = $container;
        $this->request = $container->get('request_stack')->getMasterRequest();
    }

    /**
     * {@inheritDoc}
     */
    public function getName()
    {
        return 'app_' . self::EXTENSION_NAME;
    }

    /**
     * {@inheritDoc}
     */
    public function getFunctions()
    {
        return array(
            new Twig_SimpleFunction(self::EXTENSION_NAME, array($this, 'twigHrefLangtags'), array('is_safe' => array('html'))),
            new Twig_SimpleFunction(self::EXTENSION_NAME . '_data', array($this, 'twigHrefLangtagsData')),
        );
    }

    /**
     * Get Href Lang Tags
     *
     * @param boolean $fallback
     *
     * @return Array
     */
    protected function getHrefLangTags($fallback = false)
    {
        if (isset($this->cache[$fallback ? 1 : 0])) {
            return $this->cache[$fallback ? 1 : 0];
        }

        $router = $this->container->get('router');

        $scheme = $this->container->getParameter('router.request_context.scheme');
        $translationData = $this->container->getParameter('visualm.attributen.vertalingen');

        $attributes = $this->request->attributes;
        $contentId = $attributes->get('_content_id');
        $routeName = $attributes->get('_route');

        $data = array();
        if (empty($contentId)) {
            if ($router->getRouteCollection()->get($routeName) !== null) {
                $uri = $router->generate($routeName, $attributes->get('_route_params'));

                foreach ($translationData as $host=>$translation) {
                    $data[$translation['']['code']] = $scheme . '://' . $host . $uri;
                }
            }
        }
        else {
            $relatedRoutes = $this->routeManager->getIndex(array(
                'content_id' => $contentId,
                'sub_id' => 'primary',
                'vertalingKey' => null,
            ));

            foreach ($relatedRoutes as $route) {
                if (null === $key = $route->getVertalingKey()) {
                    continue;
                }

                $host = $this->container->getParameter('router.request_context.host.' . $key);
                $data[$translationData[$host]['']['code']] = $scheme . '://' . $host . $route->getPath();
            }
        }

        if ($fallback) {
            $homeRoute = $router->generate('pagina_home', array());
            foreach ($translationData as $host=>$info) {
                if (!isset($data[$info['']['code']])) {
                    $data[$info['']['code']] = $scheme . '://' . $host . $homeRoute;
                }
            }
        }

        $this->cache[$fallback ? 1 : 0] = $data;

        return $data;
    }

    /**
     * Twig Href Lang Tags
     *
     * @return string
     */
    public function twigHrefLangtags()
    {
        $data = $this->getHrefLangtags();

        $output = '';
        foreach ($data as $key=>$href) {
            $output .= '<link rel="alternate" href="' . $href . '" hreflang="' . $key . '">' . "\n";
        }

        return $output . "\n";
    }

    /**
     * Twig Href Lang Tags Data
     *
     * @param boolean $fallback
     *
     * @return Array
     */
    public function twigHrefLangtagsData($fallback = false)
    {
        return $this->getHrefLangTags($fallback);
    }
}
