<?php

namespace Medienreaktor\Energize\ViewHelpers\Forms;


use Medienreaktor\Products\Domain\Repository\PageRepository;
use Medienreaktor\Products\Domain\Repository\ProductGroupRepository;
use Medienreaktor\Products\Domain\Repository\ProductRepository;
use Medienreaktor\Products\Service\CartDataService;
use Medienreaktor\Products\Service\ProductDataService;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Form\Domain\Finishers\FinisherVariableProvider;

class VariableProviderViewHelper extends \TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper
{

    /**
     * @var bool
     */
    protected $escapeOutput = false;

    /**
     * Arguments Initialization
     */
    public function initializeArguments(): void {
        $this->registerArgument('as', 'string', 'The variable name in which the data should be saved', TRUE);
        $this->registerArgument('variableProvider', 'object', 'Variable provider object from which data should be fetched', TRUE);
        $this->registerArgument('variableKey', 'string', 'Key of the element to fetch', TRUE);
    }

    /**
     * Render method
     * @return string
     */
    public function render() {

        $as = $this->arguments['as'];
        $variableProvider = $this->arguments['variableProvider'];
        $variableKey = $this->arguments['variableKey'];

        $productRepository = GeneralUtility::makeInstance(ProductRepository::class);
        $productGroupRepository = GeneralUtility::makeInstance(ProductGroupRepository::class);

        $productDataService = GeneralUtility::makeInstance(ProductDataService::class,$productRepository,$productGroupRepository);
        $pageRepository = GeneralUtility::makeInstance(PageRepository::class);

        $cartService = GeneralUtility::makeInstance(CartDataService::class, $productDataService, $pageRepository);

        $products = $cartService->getProductsFromCookie();

        $this->templateVariableContainer->add($as, count($products) === 0 ? null : $products);
        $output = $this->renderChildren();
        $this->templateVariableContainer->remove($as);
        return $output;
    }

}