<?php

declare(strict_types=1);

namespace Gls\GlsPoland\Form\DataMapper;

use Gls\GlsPoland\AdePlus\UserCredentials;
use Gls\GlsPoland\AdePlus\UserCredentialsInterface;
use Symfony\Component\Form\DataMapperInterface;
use Symfony\Component\Form\Exception\UnexpectedTypeException;

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

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

        if ($forms instanceof \Traversable) {
            $forms = iterator_to_array($forms);
        }

        $forms['username']->setData($viewData->getUsername());
        $forms['password']->setData($viewData->getPassword());
    }

    public function mapFormsToData($forms, &$viewData): void
    {
        if ($forms instanceof \Traversable) {
            $forms = iterator_to_array($forms);
        }

        $username = $this->normalize($forms['username']->getData());
        $password = $this->normalize($forms['password']->getData());

        if (null === $username && null === $password) {
            $viewData = null;
        } else {
            $viewData = new UserCredentials($username ?? '', $password ?? '');
        }
    }

    private function normalize($value): ?string
    {
        if (null === $value) {
            return null;
        }

        $value = trim((string) $value);

        return '' === $value ? null : $value;
    }
}
