<?php

namespace App\Controller\Brain;

use App\Entity\Category;
use App\Entity\Photos;
use App\Form\PhotosType;
use App\Service\PhotoUploader;

use Doctrine\ORM\EntityManagerInterface;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;

final class BrainPhotosController extends AbstractController
{
    #[Route('/brain/photos/list', name: 'brain_photos_list')]
    public function index(EntityManagerInterface $entityManager): Response 
    {
        $photos = $entityManager->getRepository(Photos::class)->findAllOrderByLatest();
        
        return $this->render('brain/photos/index.html.twig', [
            'photos' => $photos
        ]);
    }

    #[Route('/brain/photos/new', name: 'brain_photos_new')]
    public function new(EntityManagerInterface $entityManager, Request $request, PhotoUploader $photoUploader): Response
    {
        $form = $this->createForm(PhotosType::class);

        $form->handleRequest($request);

        if ($form->isSubmitted()) {
            $data = $form->getData();
            $photos = new Photos();
            $fileNames = [];

            $photos->setTitle($data->getTitle());
            $photos->setDate($data->getDate());
            $photos->setText($data->getText());
            $photos->setUrl($data->getUrl());

            $tax = $request->request->all('photos');

            if ($data->getCategory() == null) {
                $cat = $tax['category'];

                if ($cat !== null) {
                    $categoryToAdd = new Category()->setTitle($cat);
                    $photos->setCategory($categoryToAdd);
                
                    $entityManager->persist($categoryToAdd);
                }
            } else {
                $photos->setCategory($data->getCategory());
            }

            $thumbnail = $request->files->get('photos')['thumbnail'];

            $fileName = $photoUploader->upload($thumbnail, $photos->getTitle());
            $photos->setThumbnail($fileName);

            $uploadedPhotos = $request->files->get('photos')['uploads'];
      
            foreach ($uploadedPhotos as $upload) {
                $filenames[] = $photoUploader->upload($upload['file'], $photos->getTitle());
            }

            foreach ($data->getUploads() as $index => $photo) {
                $photo->setFile($filenames[$index]);
                $photos->addUpload($photo);
            }

            $entityManager->persist($photos);

            $entityManager->flush();

            return $this->redirectToRoute('brain_photos_list');
        }

        return $this->render('brain/photos/create.html.twig', [
            'action' => 'New',
            'form' => $form
        ]);
    }

    #[Route('/brain/photos/edit/{id}', name: 'brain_photos_edit')]
    public function edit(EntityManagerInterface $entityManager, string $id, Request $request, PhotoUploader $photoUploader): Response
    {

        $photos = $entityManager->getRepository(Photos::class)->findOneBy(['id' => $id]);

        $form = $this->createForm(PhotosType::class, $photos);

        $form->handleRequest($request);
        /* TODO handle editing! */
        /*if (!$form->isSubmitted() && $photos->getUploads()) {
            $dirName = 'uploads/' . strtolower(str_replace(' ', '_', $photos->getTitle()));
            $form->setData(['uploads' => $dirName . '/' . $photos->getUploads()[0]->getFile()]);
        } */

        if ($form->isSubmitted()) {
            $data = $form->getData();
            $photos = new Photos();
            $fileNames = [];

            $photos->setTitle($data->getTitle());
            
            $uploadedPhotos = $request->files->get('photos')['uploads'];

            foreach ($uploadedPhotos as $upload) {
                $filenames[] = $photoUploader->upload($upload['file'], $photos->getTitle());
            }

            foreach ($data->getUploads() as $index => $photo) {
                $photo->setFile($filenames[$index]);
            }
            
            //$entityManager->persist($data);

            $entityManager->flush();

            return $this->redirectToRoute('brain_photos_list');
        }

        return $this->render('brain/photos/create.html.twig', [
            'action' => 'Edit',
            'form' => $form
        ]);
    }

    private function handleFilenameToFileConversion(string $directory, array $uploads)
    {

    }

}
