<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Plugins\Model;


use Magento\Framework\Api\ExtensibleDataInterface;
use Magento\Framework\Reflection\DataObjectProcessor;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Quote\Api\Data\AddressInterface;
use Magento\Quote\Api\Data\EstimateAddressInterface;
use Magento\Quote\Model\Quote;
use Magento\Quote\Model\ShippingMethodManagement;

/**
 *
 */
class  PrefillAddress
{
    /**
     * @var \Magento\Quote\Api\CartRepositoryInterface
     */
    private $cartRepository;
    /**
     * @var \Magento\Framework\Reflection\DataObjectProcessor
     */
    private $dataObjectProcessor;

    /**
     * @param \Magento\Quote\Api\CartRepositoryInterface $cartRepository
     * @param \Magento\Framework\Reflection\DataObjectProcessor $dataObjectProcessor
     */
    public function __construct(
        CartRepositoryInterface $cartRepository,
        DataObjectProcessor $dataObjectProcessor
    ) {
        $this->cartRepository = $cartRepository;
        $this->dataObjectProcessor = $dataObjectProcessor;
    }

    /**
     * @return array
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     * @see \Magento\Quote\Model\ShippingMethodManagement::estimateByExtendedAddress
     */
    public function beforeEstimateByExtendedAddress(
        ShippingMethodManagement $subject,
        $cartId,
        AddressInterface $address
    ) {
        /** @var Quote $quote */
        $quote = $this->cartRepository->getActive($cartId);

        if ($quote->isVirtual() || $quote->getItemsCount() == 0) {
            return null;
        }

        if(!$quote->getShippingAddress()){
            return null;
        }

        $data = $this->extractAddressData($quote->getShippingAddress());

        foreach ($address->getData() as $key => $value) {
            if (empty($value)) {
                continue;
            }
            $data[$key] = $value;
        }
        $address->addData($data);

        return [$cartId, $address];
    }

    public function extractAddressData($address)
    {
        $className = \Magento\Customer\Api\Data\AddressInterface::class;
        if ($address instanceof AddressInterface) {
            $className = AddressInterface::class;
        } elseif ($address instanceof EstimateAddressInterface) {
            $className = EstimateAddressInterface::class;
        }

        $addressData = $this->dataObjectProcessor->buildOutputDataArray(
            $address,
            $className
        );
        unset($addressData[ExtensibleDataInterface::EXTENSION_ATTRIBUTES_KEY]);

        return $addressData;
    }
}