<?php

namespace Internetgalerie\IgDatapoolFe\ViewHelpers;

use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractTagBasedViewHelper;
use Internetgalerie\IgDatapoolFe\Services\SearchLogicService;
use Internetgalerie\IgDatapoolFe\Utility\NeedfulThings;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Mvc\Web\Routing\UriBuilder;


/**
 * Creates a Sort-Link Header
 */
class SortHeaderViewHelper extends AbstractTagBasedViewHelper
{
    use ViewHelperTrait;

    /**
     * is it initialized? this is set to true, if the Repository::initAutoSorting($query) method is called
     * if false, a warning is displayed.
     */
    public static $isInitializedInQuery = false;

    /**
     * @var SearchLogicService
     */
    protected $searchLogicService;

    /**
     * @var string
     */
    protected $tagName = 'a';

    /**
     * @param SearchLogicService $searchLogicService
     */
    public function injectSearchLogicService(SearchLogicService $searchLogicService): void
    {
        $this->searchLogicService = $searchLogicService;
    }

    /**
     * Arguments initialization
     *
     * @return void
     */
    public function initializeArguments(): void
    {
        $this->registerUniversalTagAttributes();
        $this->registerTagAttribute('name', 'string', 'Specifies the name of an anchor');
        $this->registerTagAttribute('rel', 'string', 'Specifies the relationship between the current document and the linked document');
        $this->registerTagAttribute('rev', 'string', 'Specifies the relationship between the linked document and the current document');
        $this->registerTagAttribute('target', 'string', 'Specifies where to open the linked document');
        $this->registerArgument('addIcon', 'boolean', 'Do you want an icon displayed?', false, true);
        $this->registerArgument('property', 'string', 'The Property', true, '');
        $this->registerArgument('label', 'string', 'Override label', false, '');
        $this->registerArgument('pageUid', 'integer', 'pageUid of the link', false, '');
    }

    /**
     * Render a sortlink
     *
     * @return string
     * @api
     */
    public function render()
    {
        if (!self::$isInitializedInQuery) {
            echo 'You need to call <strong>$this->initAutoSorting($query);<strong> in your repository find method in order to use SortHeader.<br />';
        }
        $newSorting = $this->searchLogicService->getNewSorting($this->arguments['property'], false);


        // get the label
        $label = '';
        if ($this->arguments['label']) {
            $label = $this->arguments['label'];
        } else {
            $label = NeedfulThings::getFieldLabelByProperty($this->arguments['property']);
        }
        if (!$this->arguments['class']) {
            $class = ' dp-sortlink ';
        } else {
            $class = $this->arguments['class'];
        }

        if ($this->arguments['addIcon']) {
            $currentSorting = $this->searchLogicService->getCurrentSorting(false);
            if (isset($currentSorting['property']) && $currentSorting['property'] == $this->arguments['property']) {
                if (str_contains((string) $class, 'dp-sortlink')) {
                    $class .= ' dp-sortlink-' . intval($newSorting['order']);
                } else {
                    $class .= ' dp-sort-' . intval($newSorting['order']);
                }
            }
        }

        // controller...
        $arguments = ['@sorting' => implode('_', $newSorting)];

        $arguments = NeedfulThings::keepAndOverrideArgs($arguments, $this->renderingContext->getRequest());
        $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
        $uriBuilder
            ->reset()
            ->setRequest($this->renderingContext->getRequest())
            ->setArguments([$this->getLinkPrefix() => $arguments]);
        if ($this->arguments['pageUid']) {
            $uriBuilder->setTargetPageUid($this->arguments['pageUid']);
        }
        $uri = $uriBuilder->build();

        $this->tag->addAttribute('class', $class);
        $this->tag->addAttribute('href', $uri);
        $this->tag->setContent($label);
        $this->tag->forceClosingTag(true);
        return $this->tag->render();
    }
}
