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

use Chill\PersonBundle\Entity\PersonAltName;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\Form\DataMapperInterface;
use Symfony\Component\Form\Exception\UnexpectedTypeException;

class PersonAltNameDataMapper implements DataMapperInterface
{
    public function mapDataToForms($viewData, \Traversable $forms): void
    {
        if (null === $viewData) {
            return;
        }

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

        $mapIndexToKey = [];

        foreach ($viewData->getIterator() as $key => $altName) {
            /* @var PersonAltName $altName */
            $mapIndexToKey[$altName->getKey()] = $key;
        }

        foreach ($forms as $key => $form) {
            if (\array_key_exists($key, $mapIndexToKey)) {
                $form->setData($viewData->get($mapIndexToKey[$key])->getLabel());
            }
        }
    }

    public function mapFormsToData(\Traversable $forms, &$viewData): void
    {
        $mapIndexToKey = [];

        if (\is_array($viewData)) {
            $dataIterator = $viewData;
        } else {
            $dataIterator = $viewData instanceof ArrayCollection ?
                 $viewData->toArray() : $viewData->getIterator();
        }

        foreach ($dataIterator as $key => $altName) {
            /* @var PersonAltName $altName */
            $mapIndexToKey[$altName->getKey()] = $key;
        }

        foreach ($forms as $key => $form) {
            $isEmpty = empty($form->getData());

            if (\array_key_exists($key, $mapIndexToKey)) {
                if ($isEmpty) {
                    $viewData->remove($mapIndexToKey[$key]);
                } else {
                    $viewData->get($mapIndexToKey[$key])->setLabel($form->getData());
                }
            } else {
                if (!$isEmpty) {
                    $altName = (new PersonAltName())
                        ->setKey($key)
                        ->setLabel($form->getData());

                    if (\is_array($viewData)) {
                        $viewData[] = $altName;
                    } else {
                        $viewData->add($altName);
                    }
                }
            }
        }
    }
}
