<?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\Form\Type\DataTransformer;

use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Repository\CenterRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Symfony\Component\Form\Exception\UnexpectedTypeException;

class CenterTransformer implements DataTransformerInterface
{
    public function __construct(private readonly CenterRepository $centerRepository, private readonly bool $multiple = false) {}

    public function reverseTransform($id)
    {
        if (null === $id) {
            if ($this->multiple) {
                return new ArrayCollection();
            }

            return null;
        }

        $ids = [];

        if ($this->multiple) {
            $ids = explode(',', (string) $id);
        } else {
            $ids[] = (int) $id;
        }

        $centers = $this
            ->centerRepository
            ->findBy(['id' => $ids]);

        if ([] === $centers || \count($ids) > \count($centers)) {
            throw new TransformationFailedException(sprintf('No center found for one of those ids: %s', implode(',', $ids)));
        }

        if ($this->multiple) {
            return new ArrayCollection($centers);
        }

        return $centers[0];
    }

    public function transform($center)
    {
        if (null === $center) {
            return '';
        }

        if ($this->multiple) {
            if (!is_iterable($center)) {
                throw new UnexpectedTypeException($center, \Traversable::class);
            }
            $ids = [];

            foreach ($center as $c) {
                $ids[] = $c->getId();
            }

            return implode(',', $ids);
        }

        if (!$center instanceof Center) {
            throw new UnexpectedTypeException($center, Center::class);
        }

        return (string) $center->getId();
    }
}
