<?php
namespace Medienreaktor\Products\Controller;

use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Extbase\Http\ForwardResponse;

/***
 *
 * This file is part of the "Products" Extension for TYPO3 CMS.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 *  (c) 2017 Daniel Kestler &lt;daniel.kestler@medienreaktor&gt;, medienreaktor GmbH
 *
 ***/

/**
 * DownloadController
 */
class DownloadController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
{
    /**
     * productRepository
     *
     * @var \Medienreaktor\Products\Domain\Repository\ProductRepository
     */
    protected $productRepository = null;

    /**
     * productGroupRepository
     *
     * @var \Medienreaktor\Products\Domain\Repository\ProductGroupRepository
     */
    protected $productGroupRepository = null;
    public function __construct(\Medienreaktor\Products\Domain\Repository\ProductRepository $productRepository, \Medienreaktor\Products\Domain\Repository\ProductGroupRepository $productGroupRepository)
    {
        $this->productRepository = $productRepository;
        $this->productGroupRepository = $productGroupRepository;
    }

    /**
     * action list
     *
     * @return void
     */
    public function listAction(): \Psr\Http\Message\ResponseInterface
    {
        $products = $this->productRepository->findAll();
        $this->view->assign('products', $products);
        return $this->htmlResponse();
    }

    /**
     * switchable Controller Migration
     *
     * @return ForwardResponse|ResponseInterface
     */
    public function switchableAction()
    {
        // Wert für 'switchableControllerActions' aus flexForm holen
        $cObjData = \nn\t3::Tsfe()->cObjData( $this->request );
        $ffData = \nn\t3::FlexForm()->parse($cObjData['pi_flexform']);

        // ... und an passende Action weiterleiten
        $action = preg_replace('/[^>]*>(.*)/', '\1', $ffData['switchableControllerActions']);
        $methodName = "{$action}Action";

        if (!method_exists($this, $methodName)) {
            return $this->htmlResponse("PayloadController->{$methodName}() exisitert nicht.");
        }

        return new ForwardResponse( $action );
    }
}
