<?php
namespace Newland\Toubiz\Poi\Neos\Tests\Unit\Controller;

/*
 * This file is part of the "toubiz-poi-neos" package.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 */

use Neos\ContentRepository\Domain\Model\Node;
use Neos\Flow\Http\Request;
use Neos\Flow\Http\Response;
use Neos\Flow\Http\Uri;
use Neos\Flow\Mvc\ActionRequest;
use Neos\Flow\Mvc\Controller\ActionController;
use Neos\Flow\Mvc\View\ViewInterface;
use Neos\Flow\Tests\FunctionalTestCase;
use Newland\NeosTestingHelpers\InteractsWithNodes;
use Newland\Toubiz\Poi\Neos\Tests\Unit\ViewHelpers\Widget\Controller\Mock\MockView;
use Newland\Toubiz\Sync\Neos\Tests\Factory\ArticleFactory;

abstract class ControllerBaseTest extends FunctionalTestCase
{
    protected static $testablePersistenceEnabled = true;
    use InteractsWithNodes;

    /** @var MockView */
    protected $view;

    /** @var ArticleFactory */
    protected $articleFactory;

    /** @var Node */
    protected $node;

    /** @var ActionController */
    protected $subject;

    /** @var string */
    protected $subjectClass;

    public function setUp(): void
    {
        parent::setUp();

        $this->articleFactory = new ArticleFactory($this->objectManager);

        $this->subject = $this->objectManager->get($this->subjectClass);
        $this->inject($this->subject, 'view', $this->getView());

        $this->node = $this->initializeNode('/sites/foo', null, null, [], 'de');
    }

    protected function callAction(string $action, array $arguments, array $properties): Response
    {
        $request = new ActionRequest(Request::create(new Uri('http://localhost')));
        $request->setControllerActionName($action);

        foreach ($this->node->getProperties() as $key => $value) {
            $this->node->removeProperty($key);
        }
        foreach ($properties as $key => $value) {
            $this->node->setProperty($key, $value);
        }

        $this->persistNode($this->node);
        $request->setArgument('node', $this->node->getContextPath());
        $request->setArgument('__node', $this->node);

        $response = new Response();

        $this->subject->processRequest($request, $response);
        return $response;
    }

    abstract protected function getView(): ViewInterface;
}
