<?php

declare(strict_types=1);

/*
 * Copyright (C) 2021 Daniel Siepmann <coding@daniel-siepmann.de>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

namespace DanielSiepmann\DsSite\Frontend\DataProcessing;

use TYPO3\CMS\Core\Utility\ArrayUtility;
use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
use TYPO3\CMS\Frontend\ContentObject\DataProcessorInterface;

/**
 * SQLite does not support natural sorting.
 * Yet we wanna have that, e.g. for TYPO3 compatible version to have 11, 10, 9, 8 instead of 10, 11, 8, 9.
 *
 * This processor allows to sort a given variable $variablePath by given $variableSubPath in natural reverse sorting.
 */
class NaturalSortingProcessor implements DataProcessorInterface
{
    public function process(
        ContentObjectRenderer $cObj,
        array $contentObjectConfiguration,
        array $processorConfiguration,
        array $processedData
    ) {
        $variablePath = $cObj->stdWrapValue('variablePath', $processorConfiguration, '');
        if (is_string($variablePath) === false) {
            throw new \Exception('Variable path needs to be string.', 1663760889);
        }

        $variableSubPath = $cObj->stdWrapValue('variableSubPath', $processorConfiguration, '');
        if (is_string($variableSubPath) === false) {
            throw new \Exception('Variable Sub Path needs to be string.', 1663760908);
        }

        if ($variablePath === '' || $variableSubPath === '') {
            throw new \Exception('Provide variablePath as well as variableSubPath.', 1638373263);
        }

        if (ArrayUtility::isValidPath($processedData, $variablePath) === false) {
            return $processedData;
        }

        $valuesToSort = ArrayUtility::getValueByPath($processedData, $variablePath);
        usort($valuesToSort, function (array $variable1, array $variable2) use ($variableSubPath) {
            $value1 = ArrayUtility::getValueByPath($variable1, $variableSubPath);
            $value2 = ArrayUtility::getValueByPath($variable2, $variableSubPath);
            return strnatcasecmp($value2, $value1);
        });
        $processedData = ArrayUtility::setValueByPath($processedData, $variablePath, $valuesToSort);

        return $processedData;
    }
}