<?php

namespace DanielSiepmann\DsSite\Frontend\DataProcessing;

/*
 * Copyright (C) 2020 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.
 */

use TYPO3\CMS\Core\Database\Query\QueryBuilder;
use TYPO3\CMS\Core\Database\Query\QueryHelper;
use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
use TYPO3\CMS\Frontend\ContentObject\DataProcessorInterface;

class CategoriesCounts implements DataProcessorInterface
{
    /**
     * @var QueryBuilder
     */
    private $queryBuilder;

    public function __construct(QueryBuilder $queryBuilder)
    {
        $this->queryBuilder = $queryBuilder;
    }

    public function process(
        ContentObjectRenderer $cObj,
        array $contentObjectConfiguration,
        array $processorConfiguration,
        array $processedData
    ) {
        $as = $cObj->stdWrapValue('as', $processorConfiguration, 'categories');
        $parent = $cObj->stdWrapValue('parent', $processorConfiguration, '');
        $orderBy = $cObj->stdWrapValue('orderBy', $processorConfiguration, 'count desc');

        if ($parent === '') {
            throw new \InvalidArgumentException('No "parent" given.', 1600988668);
        }

        $processedData[$as] = $this->getCategoriesCount(
            $parent,
            $orderBy
        );

        return $processedData;
    }

    private function getCategoriesCount(
        int $parentId,
        string $orderBy
    ): array {
        $queryBuilder = clone $this->queryBuilder;

        $queryBuilder->select('category.*');
        $queryBuilder->addSelectLiteral('count(mm.uid_foreign) as count');
        $queryBuilder->from('pages');
        $queryBuilder->leftJoin(
            'pages',
            'sys_category_record_mm',
            'mm',
            'pages.uid = mm.uid_foreign',
        );
        $queryBuilder->leftJoin(
            'mm',
            'sys_category',
            'category',
            'mm.uid_local = category.uid',
        );
        $queryBuilder->where(
            $queryBuilder->expr()->eq(
                'category.parent',
                $queryBuilder->createNamedParameter($parentId)
            )
        );
        $queryBuilder->groupBy('category.uid');

        foreach (QueryHelper::parseOrderBy($orderBy) as $orderBy) {
            $queryBuilder->addOrderBy($orderBy[0], $orderBy[1]);
        }

        $statement = $queryBuilder->execute();

        $categories = [];
        while ($category = $statement->fetch()) {
            $categories[] = [
                'data' => $category,
            ];
        }

        return $categories;
    }
}