<?php
namespace Wga\Core\XClass\ViewHelpers;

/*
 * This file is part of the FluidTYPO3/Vhs project under GPLv2 or later.
 *
 * For the full copyright and license information, please read the
 * LICENSE.md file that was distributed with this source code.
 */

use FluidTYPO3\Vhs\ViewHelpers\Page\BreadCrumbViewHelper as BaseBreadCrumbViewHelper;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\RootlineUtility;
use Wga\Core\Utility\DatabaseUtility;
use Wga\Core\Utility\FrontendUtility;

/**
 * ViewHelper to make a breadcrumb link set from a pageUid, automatic or manual.
 */
class BreadCrumbViewHelper extends BaseBreadCrumbViewHelper
{
    /**
     * @return string
     */
    public function render()
    {
		// @extensionScannerIgnoreLine
        $pageUid = $this->arguments['pageUid'] > 0 ? $this->arguments['pageUid'] : $GLOBALS['TSFE']->id;
		$rootlineUtility = GeneralUtility::makeInstance(RootlineUtility::class, $pageUid);
        $entryLevel = $this->arguments['entryLevel'];
        $endLevel = $this->arguments['endLevel'];
        $rawRootLineData = $rootlineUtility->get();
        $rawRootLineData = array_reverse($rawRootLineData);
        $rawRootLineData = array_slice($rawRootLineData, $entryLevel, $endLevel);
        $rootLineData = [];
        $showHidden = (boolean) $this->arguments['showHiddenInMenu'];
        $spacerDoktype = $this->pageService->readPageRepositoryConstant('DOKTYPE_SPACER');
        foreach ($rawRootLineData as $record) {
            $isHidden = (boolean) $record['nav_hide'];

            if (true === (boolean) $this->arguments['includeSpacers']) {
                $isAllowedDoktype = (int) $record['doktype'] <= $spacerDoktype;
            } else {
                $isAllowedDoktype = (int) $record['doktype'] < $spacerDoktype;
            }

            if ((true === $showHidden && true === $isHidden || false === $isHidden) && true === $isAllowedDoktype) {
                array_push($rootLineData, $record);
            }
        }
        $rootLine = $this->parseMenu($rootLineData);
        if (0 === count($rootLine)) {
            return null;
        }

        if ($GLOBALS['pageMode'] == 'DetailPage') {
            $detailPageConfig = GeneralUtility::makeInstance(
                FrontendUtility::class
            )->getTyposcriptConfiguration()['breadCrumb'];
            foreach ($detailPageConfig as $key => $values) {
                if ($_GET[$key]) {
                    $values['uid'] = $_GET[$key][strtolower($_GET[$key]['controller'])];
                    $rootLine[] = [
                        'title' => $this->getTitle($values)
                    ];
                }
            }
        }

        $this->backupVariables();
        $this->renderingContext->getVariableProvider()->add($this->arguments['as'], $rootLine);
        $output = $this->renderContent($rootLine);
        $this->renderingContext->getVariableProvider()->remove($this->arguments['as']);
        $this->restoreVariables();

        return $output;
    }

    /**
     * @param $config
     * @return false|mixed
     * @throws \Doctrine\DBAL\DBALException
     * @throws \Doctrine\DBAL\Driver\Exception
     */
    public function getTitle($config)
    {
        $queryBuilder = DatabaseUtility::getQueryBuilderForTable($config['table']);
        $statement = $queryBuilder->select($config['field'])
            ->from($config['table'])
            ->where(
                $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($config['uid']))
            )->execute()->fetchOne();

        return $statement;
    }
}
