<?php
namespace Medienreaktor\Products\Controller;

use Medienreaktor\Products\Domain\Model\Product;
use Medienreaktor\Products\Domain\Model\ProductGroup;
use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Http\ForwardResponse;
use TYPO3\CMS\Extbase\Utility\DebuggerUtility;

/***
 *
 * 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
 *
 ***/

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

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


    /**
     * action index
     *
     * @return void
     */
    public function indexAction(): \Psr\Http\Message\ResponseInterface
    {
        return $this->htmlResponse();
    }

    public function sidebarAction(): \Psr\Http\Message\ResponseInterface
    {
        $products = $this->cartDataService->getProductsFromCookie();
        $this->view->assign("products", $products);
        return $this->htmlResponse();
    }

    /**
     * @return void
     */
    public function performAction(): \Psr\Http\Message\ResponseInterface
    {
        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 );

        if(isset($cObjData['pi_flexform'])){
            $ffData = \nn\t3::FlexForm()->parse($cObjData['pi_flexform']);
            // ... und an passende Action weiterleiten
            $action = preg_replace('/[^>]*>(.*)/', '\1', $ffData['switchableControllerActions']);
        } else if($cObjData["is_siteroot"] == 1){
            $action = "sidebar";
        } else {
            $action = "sidebar";
        }


        $methodName = "{$action}Action";

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

        return new ForwardResponse( $action );
    }

}
