<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

namespace Shopware\Plugins\ViisonShippingCommon\Components;

use Doctrine\ORM\EntityManager;
use Shopware\Models\Country\Country;
use Shopware\Models\Country\State;
use Shopware\Plugins\ViisonShippingCommon\Classes\Types\Address;
use VIISON\AddressSplitter\AddressSplitter;
use VIISON\AddressSplitter\Exceptions\SplittingException;

class AddressFactory
{
    /**
     * @var EntityManager
     */
    private $entityManager;

    public function __construct(EntityManager $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    /**
     * Creates an address object from an address array which comes from an ExtJS request or pickware mobile.
     *
     * @param array $addressArray
     * @return Address
     */
    public function getAddressFromAddressArray(array $addressArray)
    {
        $address = new Address();
        $address->setSalutation($addressArray['salutation']);
        $address->setCompany($addressArray['company']);
        $address->setDepartment($addressArray['department']);
        $address->setFirstName($addressArray['firstname']);
        $address->setLastName($addressArray['lastname']);
        $address->setStreetName($addressArray['street']);
        $address->setHouseNumber($addressArray['streetnumber']);
        $address->setZipCode($addressArray['zipcode']);
        $address->setCity($addressArray['city']);
        $address->setPhoneNumber($addressArray['phone']);
        $address->setAdditionOne($addressArray['additionaladdressline']);
        $address->setEmailAddress($addressArray['email']);
        $stateId = $addressArray['stateid'] ?: $addressArray['stateID'];
        if ($stateId) {
            /** @var State|null $state */
            $state = $this->entityManager->find('Shopware\\Models\\Country\\State', $stateId);
            $address->setState($state);
        }
        $countryId = $addressArray['countryid'] ?: $addressArray['countryId'];
        if ($countryId) {
            /** @var Country|null $country */
            $country = $this->entityManager->find('Shopware\\Models\\Country\\Country', $countryId);
            $address->setCountry($country);
        }

        try {
            $houseNumberParts = AddressSplitter::splitHouseNumber($addressArray['streetnumber']);
            $address->setHouseNumberBase($houseNumberParts['base']);
            $address->setHouseNumberExtension($houseNumberParts['extension']);
        } catch (SplittingException $e) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
            // Do nothing
        }

        return $address;
    }
}
