<?php
/**
 * Menu Controller
 *
 * @author Elze Kool <info@visualmedia.nl>
 */

namespace VisualM\ManagementBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
use VisualM\ManagementBundle\Routing\LinkGeneratorInterface;

/**
 * Menu Controller
 *
 * @author Elze Kool <info@visualmedia.nl>
 */
class MenuController extends Controller implements LinkGeneratorInterface
{
    /** @var LinkGeneratorInterface */
    protected $frontendLinkGenerator;

    /**
     * Render Menu
     *
     * @return Response Response
     */
    public function renderAction()
    {        
        if (null === ($menu_service_name = $this->container->getParameter('visual_m_management_menu_provider'))) {
            return new Response('');
        }

        $menu_provider = $this->container->get($menu_service_name);
        $items = $menu_provider->getItems();
        $request_stack = $this->container->get('request_stack');

        $authChecker = $this->container->get('security.authorization_checker');

        return $this->render('VisualMManagementBundle:Menu:menu.html.twig', [
            'items' => $items,
            'request' => $request_stack->getMasterRequest(),
            'auth_checker' => $authChecker
        ]);

    }

    /**
     * Render Frontend Link
     *
     * @return Response Response
     */
    public function renderAdminAction()
    {
        $request = $this->container->get('request_stack')->getMasterRequest();
        $frontendLink = null;
        if (null !== ($frontend_route = $this->container->getParameter('visual_m_management_frontend_route'))) {
            $frontendLink = $this->getFrontendLinkGenerator()
                ->generateLink($request, $this->container->get('router'), $frontend_route);
        }

        return $this->render('VisualMManagementBundle:Menu:admin.html.twig', [
            'frontend_link' => $frontendLink,
            'taalkeuze' => ($this->container->has('visualm.attributen.controller.taalkeuze')
                && $request->isMethod(Request::METHOD_GET)),
        ]);
    }

    /** {@inheritdoc} */
    public function generateLink(Request $request, RouterInterface $router, $frontend_route)
    {
        return $router->generate($frontend_route, [], UrlGeneratorInterface::ABSOLUTE_URL);
    }

    /**
     * @param LinkGeneratorInterface $frontendLinkGenerator
     */
    public function setFrontendLinkGenerator(LinkGeneratorInterface $frontendLinkGenerator)
    {
        $this->frontendLinkGenerator = $frontendLinkGenerator;
    }

    /**
     * @return LinkGeneratorInterface
     */
    protected function getFrontendLinkGenerator()
    {
        return null === $this->frontendLinkGenerator
            ? $this
            : $this->frontendLinkGenerator;
    }


}