<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\CustomFieldsBundle\Tests;

use Chill\CustomFieldsBundle\Entity\CustomField;
use Symfony\Component\DomCrawler\Crawler;

/**
 * Give useful method to prepare tests regarding custom fields.
 */
trait CustomFieldTestHelper
{
    /**
     * Prepare a crawler containing the rendering of a customField.
     *
     * @internal This method will mock a customFieldGroup containing $field, and
     * rendering the customfield, using Type\CustomFieldType, to a simple form row
     *
     * @param type $locale
     *
     * @return Crawler
     */
    public function getCrawlerForField(CustomField $field, $locale = 'en')
    {
        $kernel = static::$kernel;

        // check a kernel is accessible
        $customFieldsGroup = $this->createMock(\Chill\CustomFieldsBundle\Entity\CustomFieldsGroup::class);
        $customFieldsGroup->expects($this->once())
            ->method('getActiveCustomFields')
            ->will($this->returnValue([$field]));

        $request = $this->createMock(\Symfony\Component\HttpFoundation\Request::class);
        $request->expects($this->any())
            ->method('getLocale')
            ->will($this->returnValue($locale));

        $kernel->getContainer()->get('request_stack')->push($request);

        $builder = $kernel->getContainer()->get('form.factory')->createBuilder();
        $form = $builder->add(
            'tested',
            'custom_field',
            ['group' => $customFieldsGroup]
        )
            ->getForm();

        $kernel->getContainer()->get('twig.loader')
            ->addPath($kernel->getContainer()->getParameter('kernel.root_dir').
                '/Resources/views/', $namespace = 'test');

        $content = $kernel
            ->getContainer()->get('templating')
            ->render('@test/CustomField/simple_form_render.html.twig', [
                'form' => $form->createView(),
                'inputKeys' => ['tested'],
            ]);

        $crawler = new Crawler();
        $crawler->addHtmlContent($content);

        return $crawler;
    }
}
