<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\Checkout\Presenter;

use Gls\GlsPoland\AdePlus\ParcelShop\ParcelShop;
use Gls\GlsPoland\PrestaShop\Configuration\ShopConfigurationRepository;
use Gls\GlsPoland\PrestaShop\ObjectModel\Repository\CountryRepository;

final class ParcelShopAddressPresenter
{
    private $countryRepository;
    private $configuration;

    public function __construct(CountryRepository $countryRepository, ShopConfigurationRepository $configuration)
    {
        $this->countryRepository = $countryRepository;
        $this->configuration = $configuration;
    }

    public function present(ParcelShop $parcelShop, bool $html = true): string
    {
        $address = $this->createAddress($parcelShop);
        $newLineSeparator = $html ? '<br/>' : "\n";

        return \AddressFormat::generateAddress($address, [], $newLineSeparator);
    }

    private function createAddress(ParcelShop $parcelShop): \Address
    {
        $address = new \Address();

        $address->firstname = $this->formatParcelShopName($parcelShop);
        $address->lastname = '';
        $address->address1 = $parcelShop->getStreet();
        $address->city = $parcelShop->getCity();
        $address->postcode = $parcelShop->getZipCode();
        $address->id_country = $this->getCountryId($parcelShop->getCountry());
        $address->phone = $parcelShop->getPhone();

        return $address;
    }

    private function getCountryId(string $isoCode): int
    {
        if (null === $country = $this->countryRepository->findOneByIsoCode($isoCode)) {
            return $this->configuration->getDefaultCountryId();
        }

        return (int) $country->id;
    }

    private function formatParcelShopName(ParcelShop $parcelShop): string
    {
        return trim(sprintf('%s %s %s', $parcelShop->getName1(), $parcelShop->getName2(), $parcelShop->getName3()));
    }
}
