<?php

namespace App\Controller;

use App\Entity\SolidoumeParameter;
use App\Form\Type\SolidoumeParameterFormType;
use App\Utils\CustomEntityManager;
use Ramsey\Uuid\Uuid;
use Sonata\AdminBundle\Controller\CRUDController;
use Symfony\Component\Security\Core\Security;

class SolidoumeParameterController extends CRUDController
{
    protected $em;
    protected $security;

    public function __construct(CustomEntityManager $em, Security $security)
    {
        $this->em = $em;
        $this->security = $security;
    }

    /**
     * List action.
     *
     * @throws AccessDeniedException If access is not granted
     *
     * @return Response
     */
    public function listAction()
    {
        $request = $this->getRequest();

        $data = $this->em->getRepository(SolidoumeParameter::class)->findTheOne();
        $oldData = null;
        if (!empty($data)) {
            $oldData = clone $data;
        }
        $form = $this->createForm(SolidoumeParameterFormType::class, $data);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            if (null != $oldData) {
                $oldData->setEnabled(false);
                $this->em->persist($oldData);
                $this->em->flush();
            }
            $solidoumeParameter = $form->getData();
            $solidoumeParameter->setId(Uuid::uuid4());
            $solidoumeParameter->setEnabled(true);
            $this->em->persist($solidoumeParameter);
            $this->em->flush();

            $this->addFlash(
                'sonata_flash_success',
                'Paramètres de la sécurite sociale alimentaire bien validés !'
            );

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

        $template = $this->admin->getTemplate('list');

        return $this->renderWithExtraParams($template, [
            'action' => 'list',
            'form' => $form->createView(),
        ], null);
    }
}
