<?php

namespace Internetgalerie\IgDatapoolFe\ViewHelpers\Widget\Controller;

use TYPO3\CMS\Fluid\Core\Widget\AbstractWidgetController;
use TYPO3\CMS\Core\Utility\ArrayUtility;
use Exception;
use TYPO3\CMS\Extbase\Reflection\ObjectAccess;
use TYPO3\CMS\Extbase\Mvc\View\ViewInterface;
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
use TYPO3\CMS\Extbase\Persistence\QueryResultInterface;

class AbcnateController extends AbstractWidgetController
{
    /**
     * @var array
     */
    protected $configuration = ['insertAbove' => false, 'insertBelow' => true, 'filter' => [' ']];

    /**
     * @var QueryResultInterface
     */
    protected $objects;

    /**
     * @var integer
     */
    protected $currentChar = null;

    /**
     * Parent Request
     */
    protected $parentRequest;

    /**
     * Property
     */
    protected $property;

    /**
     * @return void
     */
    public function initializeAction(): void
    {
        $this -> objects = $this -> widgetConfiguration['objects'];
        ArrayUtility::mergeRecursiveWithOverrule($this -> configuration, $this -> widgetConfiguration['configuration'], false);
        $this -> property = $this -> widgetConfiguration['property'];
        ;
        if (!$this -> property) {
            throw new Exception('Abcnator: Kein Property gesetzt!');
        }
    }

    /**
     * @param  string $currentChar
     * @return void
     */
    public function indexAction($currentChar = null): void
    {
        $this -> currentChar = $currentChar;
        if ($this -> currentChar) {
            // modify query
            $query = $this -> objects -> getQuery();
            $oldConstraints = $query -> getConstraint();
            $newConstraints = $query -> like($this -> property, $this -> currentChar . '%');
            if ($oldConstraints) {
                $newConstraints = $query -> logicalAnd([$oldConstraints], $newConstraints);
            }
            $query -> matching($newConstraints);
            $modifiedObjects = $query -> execute();
        } else {
            $modifiedObjects = $this -> objects;
        }

        $this -> view -> assign('contentArguments', [$this -> widgetConfiguration['as'] => $modifiedObjects]);
        $this -> view -> assign('configuration', $this -> configuration);
        $this -> view -> assign('abcList', $this -> buildAbcList($currentChar));
    }

    protected function buildAbcList($currentChar)
    {
        $abc = [];
        foreach ($this->objects as $o) {
            $letter = strtoupper((string) ObjectAccess::getPropertyPath($o, $this -> property)[0]);
            if (in_array($letter, $this -> configuration['filter'])) {
                continue;
            }
            $abc[$letter] = $currentChar == $letter;
        }
        ksort($abc);
        return $abc;
    }

    public function setParentRequest($request): void
    {
        $this -> parentRequest = $request;
    }

    /**
     * Allows the widget template root path to be overriden via the framework configuration,
     * e.g. plugin.tx_extension.view.widget.<WidgetViewHelperClassName>.templateRootPath
     *
     * @param  \TYPO3\CMS\Extbase\Mvc\View\ViewInterface $view
     * @return void
     */
    protected function setViewConfiguration(ViewInterface $view)
    {
        $rootPath = ExtensionManagementUtility::extPath($this -> parentRequest -> getControllerExtensionKey());
        $templatePathAndFilename = $rootPath . 'Resources/Private/Partials/' . $this -> parentRequest -> getControllerName() . '/AbcBrowser.html';
        if (!file_exists($templatePathAndFilename)) {
            $templatePathAndFilename = $rootPath . 'Resources/Private/Partials/AbcBrowser.html';
        }
        $view -> setTemplatePathAndFilename($templatePathAndFilename);
    }
}
