<?php

namespace App\Controller;

use App\Repository\ProjectRepository;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Contracts\Translation\TranslatorInterface;

class HomeController extends AbstractController
{
    // Page d’accueil du site
    #[Route('/', name: 'app_home')]
    public function index(ProjectRepository $projectRepository): Response
    {
        $popularProjects = $projectRepository->findSomeOrderedByPopularity();

        return $this->render('home/index.html.twig', [
            'popularProjects' => $popularProjects,
        ]);
    }

    #[Route('/{locale}', name: 'app_locale', requirements: ['locale' => '(fr|en)'])]
    public function changeLocale(Request $request, $locale): Response
    {
        $request->getSession()->set('_locale', $locale);

        if ($request->headers->has('Referer')) {
            return $this->redirect($request->headers->get('Referer'));
        } else {
            return $this->redirectToRoute('app_home');
        }
    }

    // Page d’erreur
    public function error(Request $request, $exception, $logger = null): Response
    {
        $this->addFlash('danger', $exception->getMessage()); // . ' ' . $exception->getFile() . ':' . $exception->getLine());

        // Si le referer est renseigné on renvoie vers celui-ci où le message d’erreur sera affiché
        if ($request->headers->has('Referer')) {
            return $this->redirect($request->headers->get('Referer'));
        }

        return $this->render('home/error.html.twig', [
        ]);
    }

    // L’oauth OSM commence ici
    #[Route('/osm/request', name: 'app_osm_request')]
    public function osmRequest(Request $request, ClientRegistry $clientRegistry): Response
    {
        // Se souvient d’où l’on vient pour pouvoir y retourner après la connexion
        if ($request->headers->has('Referer')) {
            $session = $request->getSession();
            $session->set('referer', $request->headers->get('Referer'));
        }

        return $clientRegistry
            ->getClient('openstreetmap') // cf `config/packages/knpu_oauth2_client.yaml`
            ->redirect([
                'read_prefs', // TODO est-ce qu’on a même besoin de ça ?
            ]);
    }

    // L’oauth OSM aboutit ici
    #[Route('/osm/callback', name: 'app_osm_callback')]
    public function osmCallback(Request $request, ClientRegistry $clientRegistry, TranslatorInterface $translator): Response
    {
        $client = $clientRegistry->getClient('openstreetmap');

        if ($request->query->has('error')) {
            $this->addFlash('danger', sprintf(
                $translator->trans('alert.auth_failure').' (%s)',
                $request->query->has('error_description') ? $request->query->get('error_description') : $request->query->get('error')
            ));
        } else {
            $this->addFlash('success', $translator->trans('alert.auth_success'));
        }

        $session = $request->getSession();

        return $session->has('referer') ? new RedirectResponse($session->get('referer'), Response::HTTP_TEMPORARY_REDIRECT) : $this->redirectToRoute('app_home');
    }

    // La déconnexion passe par là mais c’est pas lié à l’oauth
    #[Route('/osm/logout', name: 'app_osm_logout')]
    public function osmLogout(Request $request, Security $security): Response
    {
        return $security->logout();
    }
}
