<?php
/**
 * @author Colinet Julien
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Controller\Site;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\RouterInterface;

class LocaleController extends AbstractController
{

    private $router;
    private $session;

    public function __construct(RouterInterface $router, SessionInterface $session)
    {
        $this->router = $router;
        $this->session = $session;
    }

    /**
     * @Route("/request/locale/{locale}", name="setLocale")
     * @param Request $request
     * @param null $locale
     *
     * @return RedirectResponse
     */
    public function setLocaleAction(Request $request, $locale = null)
    {
        if($locale)
        {
            $this->session->set('_locale', $locale);
        }

        $url = $request->headers->get('referer');
        if(empty($url))
        {
            $url = $this->router->generate('homepage');
        }

        return new RedirectResponse($url);
    }
}