<?php
namespace Medienreaktor\Products\ViewHelpers;

use TYPO3\CMS\Core\Context\Context;
use TYPO3\CMS\Core\Domain\Repository\PageRepository;
use TYPO3\CMS\Core\Utility\GeneralUtility;

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

    public function __construct(\Medienreaktor\Products\Domain\Repository\ProductGroupRepository $productGroupRepository, \TYPO3\CMS\Core\Domain\Repository\PageRepository $pageRepository)
 {
     $this->productGroupRepository = $productGroupRepository;
     $this->pageRepository = $pageRepository;
 }
 /**
	* Arguments Initialization
	*/
	public function initializeArguments(): void {
		$this->registerArgument('as', 'Array', 'The variable name the product groups should be saved', TRUE);
	}

    /**
     * productGroupRepository
     *
     * @var \Medienreaktor\Products\Domain\Repository\ProductGroupRepository
     */
    protected $productGroupRepository = null;

    /**
     * pageRepository
     *
     * @var PageRepository
     */
    protected $pageRepository = null;

    /**
     * Returns a specific collection referenced by uid.
     *
     * @return mixed
     */
    public function render()
    {
		$as			= $this->arguments['as'];

        $productGroups = $this->productGroupRepository->findAll();

        $return = [];
        $return[] = ['value' => '', 'label' => ''];

        foreach($productGroups as $productGroup) {

            if ($productGroup->getShowinsupport()) {
                $pageUid = $productGroup->getPid();
                $pageTitle = $this->getPageTitleByPageUid($pageUid);

                $return[] = [
                    'value' => $productGroup->getName(),
                    'label' => $pageTitle.': '.$productGroup->getName(),
                    'sort' => strtoupper($pageTitle.': '.$productGroup->getName()),
                    'options' => $productGroup->getProducts()
                ];
            }
        }

        $this->templateVariableContainer->add($as, $return);
        $output = $this->renderChildren();
        $this->templateVariableContainer->remove($as);

        return $output;
    }

    /**
     * Returns the page title for the product group (one level higher in the tree)
     *
     * @return string
     */
    protected function getPageTitleByPageUid($pageUid) {
        $page = $this->pageRepository->getPage($pageUid);
        $parentPageUid = $page['pid'];
        $parentPage = $this->pageRepository->getPage($parentPageUid);
        $parentPage = $this->pageRepository->getPageOverlay($parentPage);

        $languageAspect = GeneralUtility::makeInstance(Context::class)->getAspect('language');

        if ($languageAspect->getId() > 0) {
            $parentPage = $this->pageRepository->getPage($parentPage['uid']);
            $parentPageTitle = $parentPage['title'];
        }

        return $parentPage['title'];
    }
}
