<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Serializer\Normalizer;

use Chill\MainBundle\Serializer\Model\Collection;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class CollectionNormalizer implements NormalizerAwareInterface, NormalizerInterface
{
    use NormalizerAwareTrait;

    /**
     * @param Collection  $collection
     * @param string|null $format
     */
    public function normalize($collection, $format = null, array $context = [])
    {
        $paginator = $collection->getPaginator();

        return [
            'count' => $paginator->getTotalItems(),
            'pagination' => [
                'first' => $paginator->getCurrentPageFirstItemNumber(),
                'items_per_page' => $paginator->getItemsPerPage(),
                'next' => $paginator->hasNextPage() ? $paginator->getNextPage()->generateUrl() : null,
                'previous' => $paginator->hasPreviousPage() ? $paginator->getPreviousPage()->generateUrl() : null,
                'more' => $paginator->hasNextPage(),
            ],
            'results' => $this->normalizer->normalize($collection->getItems(), $format, $context),
        ];
    }

    public function supportsNormalization($data, $format = null): bool
    {
        return $data instanceof Collection;
    }
}
