<?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\DataMapper;

use Chill\MainBundle\Entity\Embeddable\PrivateCommentEmbeddable;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\DataMapperInterface;
use Symfony\Component\Form\Exception\UnexpectedTypeException;
use Symfony\Component\Security\Core\Security;

final class PrivateCommentDataMapper extends AbstractType implements DataMapperInterface
{
    public function __construct(private readonly Security $security) {}

    public function mapDataToForms($viewData, \Traversable $forms)
    {
        if (null === $viewData) {
            return null;
        }

        if (!$viewData instanceof PrivateCommentEmbeddable) {
            throw new UnexpectedTypeException($viewData, PrivateCommentEmbeddable::class);
        }

        $forms = iterator_to_array($forms);

        $forms['comments']->setData($viewData->getCommentForUser($this->security->getUser()));
    }

    public function mapFormsToData(\Traversable $forms, &$viewData)
    {
        $forms = iterator_to_array($forms);

        $viewData->setCommentForUser($this->security->getUser(), $forms['comments']->getData());
    }
}
