<?php

declare(strict_types=1);

namespace Gls\GlsPoland\Form\DataTransformer;

use Gls\GlsPoland\AdePlus\SenderAddress\SenderAddress;
use Gls\GlsPoland\AdePlus\SenderAddress\SenderAddressesCollection;
use Gls\GlsPoland\Consignment\DTO\AddressDetails;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

final class AddressDetailsToSenderAddressTransformer implements DataTransformerInterface
{
    private $addresses;

    public function __construct(SenderAddressesCollection $addresses = null)
    {
        $this->addresses = $addresses;
    }

    public function transform($value): ?SenderAddress
    {
        if (null === $value) {
            return null;
        }

        if (!$value instanceof AddressDetails) {
            throw new TransformationFailedException(sprintf('Expected a %s.', AddressDetails::class));
        }

        return $this->getAddressForValue($value);
    }

    public function reverseTransform($value)
    {
        if (null === $value) {
            return null;
        }

        if (!$value instanceof SenderAddress) {
            throw new TransformationFailedException(sprintf('Expected a %s.', SenderAddress::class));
        }

        return AddressDetails::fromAdeSenderAddress($value);
    }

    private function getAddressForValue(AddressDetails $addressDetails): SenderAddress
    {
        $senderAddress = $addressDetails->asAdeSenderAddress();

        if (null === $this->addresses) {
            return $senderAddress;
        }

        foreach ($this->addresses as $address) {
            if ($address == $senderAddress) {
                return $address;
            }
        }

        return $senderAddress;
    }
}
