<?php

namespace AutoAdmin\Bundle\Media\Admin\Controller;

use AutoAdmin\Bundle\Admin\Controller\Admin\EntityController;
use AutoAdmin\Bundle\Admin\Helper\FlashbagHelper;
use AutoAdmin\Bundle\Content\Model\UpdatedAtInterface;
use AutoAdmin\Bundle\Media\Model\Library\FileMediaInterface;
use AutoAdmin\Bundle\Media\Upload\MediaUploadHandler;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;

class FileMediaAdminController extends EntityController
{
    public function __construct(
        protected MediaUploadHandler $uploadHandler
    ) {
        parent::__construct();
    }

    protected function handleUpsertForm($entity, FormInterface $form, Request $request)
    {
        if (!$form->isValid()) {
            FlashbagHelper::addError($request, 'Une erreur est survenue lors de la sauvegarde de l\'entité.');

            return false;
        }

        try {
            $class = get_class($entity);
            $data = $form->getData();

            // manually trigger doctrine listeners using UpdatedAtInterface
            if ($data instanceof UpdatedAtInterface && $data->getUpdatedAt()) {
                $clone = clone $data->getUpdatedAt();
                $data->setUpdatedAt($clone);
            }

            // media handling
            if (!$this->handleUpload($data)) {
                FlashbagHelper::addError($request, 'Une erreur est survenue lors de la sauvegarde du fichier.');

                return false;
            }

            $this->em->persist($data);
            $this->em->flush();

            FlashbagHelper::addSuccess($request, 'Entité sauvegardée avec succès !');

            // redirect to default action
            $entityDefaultAction = $this->configManager->getEntityConfigByClass($class)['default_action'];

            $redirectActionSlug = $entityDefaultAction;
            if ($form->get('submit_and_return')->isClicked() === false) {
                $actionConfig = $this->configManager->getActionConfig($class, 'update');
                if ($actionConfig !== null) {
                    $redirectActionSlug = 'update';
                }
            }

            $redirectUrl = $this->adminRouter->generate(
                $entity,
                $redirectActionSlug,
                ['tab' => $request->get('tab', 'default'),]
            );

            return $this->redirect($redirectUrl);
        } catch (UniqueConstraintViolationException $exception) {
            $mapping = $this->entityHelper->getManager()->getClassMetadata($class);
            $possibleDuplicatedFields = [];
            foreach ($mapping->getFieldNames() as $name) {
                if (!empty($mapping->getFieldMapping($name)['unique'])) {
                    $possibleDuplicatedFields[] = $name;
                }
            }

            foreach ($mapping->getAssociationNames() as $name) {
                if ($mapping->isSingleValuedAssociation($name)) {
                    $possibleDuplicatedFields[] = $name;
                }
            }

            $errMessage = 'Erreur, une colonne unique est dupliquée ('.implode(', ', $possibleDuplicatedFields).')';
            FlashbagHelper::addError($request, $errMessage);
        }

        return false;
    }


    protected function handleUpload($entity)
    {
        $status = false;

        if ($entity instanceof FileMediaInterface && $entity->getFile() !== null) {
            $status = $this->uploadHandler->handle($entity);
        }

        return $status;
    }
}