<?php

namespace App\Controller\Admin;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Requirement\Requirement;
use Symfony\Component\Routing\Attribute\Route;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\String\Slugger\AsciiSlugger;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

use App\Entity\Gamemaster;
use App\Form\GamemasterType;
use App\Service\PictureService;
use App\Repository\UserRepository;
use App\Repository\GamemasterRepository;

final class GamemasterController extends AbstractController
{
    #[Route('/admin/gamemaster', name: 'app_admin_gm', methods: ['GET'])]
    public function index(GamemasterRepository $repository): Response
    {
        $gamemasters = $repository->findAll();

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

    /*
     * Supprimer un jeu
     */
    #[Route('/admin/gamemaster/{id}/delete', name: 'app_admin_gamemaster_delete', requirements: ['id' => Requirement::UUID_V7], methods: ['GET'])]
    public function delete(?Gamemaster $gamemaster, EntityManagerInterface $manager, ParameterBagInterface $params): Response
    {
        // Effacer toutes images associée
        if ($gamemaster->getPicture()) {
            $fullPath = $params->get('upload_images_directory') . '/gamemasters/' . $gamemaster->getPicture();
            unlink($fullPath);
        }
        
        $manager->remove($gamemaster);
        $manager->flush();
        
        $this->addFlash('success', 'Meneur de jeu supprimé avec succès.');
        return $this->redirectToRoute('app_admin_gm');
    }

    /*
     * Supprimer l'image un jeu
     */
    #[Route('/admin/gamemaster/{id}/del-pic', name: 'app_admin_gamemaster_del_pic', requirements: ['id' => Requirement::UUID_V7], methods: ['GET'])]
    public function deletePicture(?Gamemaster $gamemaster, EntityManagerInterface $manager, ParameterBagInterface $params): Response
    {
        // Effacer toutes images associée
        if ($gamemaster->getPicture()) {
            $fullPath = $params->get('upload_images_directory') . '/gamemasters/' . $gamemaster->getPicture();
            unlink($fullPath);
        }
        $gamemaster->setPicture(null);
        $manager->flush();
        
        $this->addFlash('success', 'Illustration supprimée avec succès.');
        return $this->redirectToRoute('app_admin_gamemaster_edit', ['id' => $gamemaster->getId()]);
    }

    /* 
     * Modifier un jeu
     */
    #[Route('/admin/gamemaster/{id}/edit', name: 'app_admin_gamemaster_edit', requirements: ['id' => Requirement::UUID_V7], methods: ['GET', 'POST'])]
    public function edit(?Gamemaster $gamemaster, Request $request, EntityManagerInterface $manager, PictureService $pictureService): Response
    {
        $form = $this->createForm(GamemasterType::class, $gamemaster);

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {

            if (!$form->get('preferedName')->getData()) {
                $gamemaster->setPreferedName($form->get('firstName')->getData() ." ". $form->get('lastName')->getData());
            }

            $slug = $form->get('slug')->getData();
            // Aucun slug n'a été proposé par l'utilisateur
            if (!$slug) {
                $slugger = new AsciiSlugger('fr_FR');
                $slug = $slugger->slug(strtolower($gamemaster->getPreferedName()));
                $gamemaster->setSlug($slug);
            }
            
            // Flag auteur, si len(authorOfGames) > 0 -> isAuthor
            if (count($form->get('authorOfGames')->getData()) > 0) {
                $gamemaster->setIsAuthor(true);
            } else {
                $gamemaster->setIsAuthor(false);
            }
            
            // Traiter l'image proposée
            $tmpPicture = $form->get('picture')->getData();
            if ($tmpPicture) {
                $picture = $pictureService->square($tmpPicture, '/gamemasters/', $slug);
                $gamemaster->setPicture($picture);
            }
            $manager->persist($gamemaster);
            $manager->flush();

            $this->addFlash('success', 'Meneur de jeu modifié avec succès.');
            return $this->redirectToRoute('app_admin_gm');
        }

        return $this->render('admin/gamemaster/edit.html.twig', [
            'form' => $form,
            'gamemaster' => $gamemaster,
        ]);
    }

    /*
     * Associer les MJ à leurs comptes utlisateurs s'il existe
     */
    #[Route('/admin/gamemaster/link', name: 'app_admin_gamemaster_link', methods: ['GET'])]
    public function link(EntityManagerInterface $manager, UserRepository $userRepo, GamemasterRepository $gmRepo): Response
    {
        $linkedAccount = 0;
        foreach ($gmRepo->findUnlinked() as $gamemaster) {
            $lookUpUser = $userRepo->findByEmail($gamemaster->getEmail());
            if ($lookUpUser) {
                $gamemaster->setLinkToUser($lookUpUser);
                $manager->persist($gamemaster);
                $manager->flush();
                $linkedAccount++;
            }
        }
        $this->addFlash('success', $linkedAccount.' comptes associés');
        return $this->redirectToRoute('app_admin_gm');
    }

    /* 
     * Ajouter un meneur de jeu
     */
    #[Route('/admin/gamemaster/add', name: 'app_admin_gamemaster_add', methods: ['GET', 'POST'])]
    public function add(Request $request, EntityManagerInterface $manager, PictureService $pictureService): Response
    {
        $gamemaster = new Gamemaster();
        $form = $this->createForm(GamemasterType::class, $gamemaster);

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {

            if (!$form->get('preferedName')->getData()) {
                $gamemaster->setPreferedName($form->get('firstName')->getData() ." ". $form->get('lastName')->getData());
            }

            $slug = $form->get('slug')->getData();
            // Aucun slug n'a été proposé par l'utilisateur
            if (!$slug) {
                $slugger = new AsciiSlugger('fr_FR');
                $slug = $slugger->slug(strtolower($gamemaster->getPreferedName()));
                $gamemaster->setSlug($slug);
            }
            
            // Flag auteur, si len(authorOfGames) > 0 -> isAuthor
            if (count($form->get('authorOfGames')->getData()) > 0) {
                $gamemaster->setIsAuthor(true);
            } else {
                $gamemaster->setIsAuthor(false);
            }

            
            // Traiter l'image proposée
            $tmpPicture = $form->get('picture')->getData();
            if ($tmpPicture) {
                $picture = $pictureService->square($tmpPicture, '/gamemasters/', $slug);
                $gamemaster->setPicture($picture);
            }
            $manager->persist($gamemaster);
            $manager->flush();

            $this->addFlash('success', 'Meneur de jeu ajouté avec succès.');
            return $this->redirectToRoute('app_admin_gm');
        }

        return $this->render('admin/gamemaster/edit.html.twig', [
            'form' => $form,
            'gamemaster' => $gamemaster,
        ]);
    }

    /*
     * API Json : checker si un MJ peut mener un jeu ! 
    
    #[Route('/api/gm-capablity', name: 'app_api_gm_capability', methods: ['GEt'])]
    public function gmCapability(Request $request, GamemasterRepository $repository): JsonResponse
    {
        $data = json_decode($request->getContent(), true);
        $gamemasterID = $data['gamemasterId'] ?? null;

        if (!$gamemasterID) {
            return new JsonResponse(['success' => false]);
        }

        // retrouver le MJ
        $gamemaster = $repository->findByStrID($gamemasterID);
        $canMaster = array_map(fn($g) => $g->getId(), $gamemaster->getGamesCanMaster()->toArray());

        return new JsonResponse(['success' => true, 'canMaster' => $canMaster]);

    } */
}
