<?php
namespace App\Controller;

use App\Form\AbstractFormManager;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormFactory;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

/**
 * Abstract class for generic controller
 */
abstract class AbstractExtendedController extends AbstractController
{

    /**
     * Create the json answer for an ajax form
     * - code : Http code
     * - error : Form error content
     * - message : A popup message to display
     * - redirect : Redirect the user to a specific URL
     * - refresh : Refresh the page
     * - reset : Reset the form
     *
     * @param array $settings
     * @return JsonResponse
     */
    protected function ajaxFormAnswer(array $settings = []): JsonResponse
    {
        $data = [
            "message" => $settings["message"] ?? "",
            "redirect" => $settings["redirect"] ?? "",
            "error" => $settings["error"] ?? "",
            "refresh" => $settings["refresh"] ?? false,
            "reset" => $settings["reset"] ?? false,
        ];

        return $this->json($data, $settings["code"] ?? Response::HTTP_OK);
    }

    /**
     * Create a form inherited from AbstractGenericForm
     *
     * @param string $name
     * @param string $type
     * @param array $options
     * @return AbstractFormManager
     */
    protected function createNamedCustomForm(string $name, string $type, array $options = []): AbstractFormManager
    {
        /** @var FormFactory $formFactory */
        $formFactory = $this->container->get('form.factory');
        $formBuilder = $formFactory->createNamedBuilder($name, FormType::class);
        return new $type($formBuilder, $options, true);
    }

    /**
     * Create a form inherited from AbstractGenericForm with get method
     *
     * @param string $name
     * @param string $type
     * @param array $options
     * @return AbstractFormManager
     */
    protected function createNamedGetCustomForm(string $name, string $type, array $options = []): AbstractFormManager
    {
        /** @var FormFactory $formFactory */
        $formFactory = $this->container->get('form.factory');
        $formBuilder = $formFactory->createNamedBuilder($name, FormType::class, [], [
            'csrf_protection' => false,
        ]);
        $formBuilder->setMethod('GET');
        return new $type($formBuilder, $options, false);
    }
}
