<?php

namespace FiloBlu\Rma\Block\Adminhtml\Rma\Edit\Tab;

use Exception;
use FiloBlu\Rma\Api\EasyReturnRepositoryInterface;
use Magento\Backend\Block\Template\Context;
use Magento\Directory\Model\RegionFactory;
use Magento\Framework\Data\FormFactory;
use Magento\Framework\Registry;
use Magento\Rma\Model\Rma;
use Magento\Sales\Api\Data\OrderAddressInterface;
use Throwable;

/**
 *
 */
class General extends \Magento\Rma\Block\Adminhtml\Rma\Edit\Tab\General
{
    /**
     * @var EasyReturnRepositoryInterface
     */
    private $easyReturnRepository;
    /**
     * @var RegionFactory
     */
    private $regionFactory;

    /**
     * General constructor.
     * @param Context $context
     * @param Registry $registry
     * @param FormFactory $formFactory
     * @param EasyReturnRepositoryInterface $easyReturnRepository
     * @param RegionFactory $regionFactory
     * @param array $data
     */
    public function __construct(
        Context                       $context,
        Registry                      $registry,
        FormFactory                   $formFactory,
        EasyReturnRepositoryInterface $easyReturnRepository,
        RegionFactory                 $regionFactory,
        array                         $data = [])
    {
        parent::__construct($context, $registry, $formFactory, $data);
        $this->easyReturnRepository = $easyReturnRepository;
        $this->regionFactory = $regionFactory;
    }


    /**
     * @return OrderAddressInterface|null
     */
    public function getPickupAddress()
    {
        try {
            /** @var Rma $rma */
            $rmaId = $this->getRequest()->getParam('id');
            $easyReturn = $this->easyReturnRepository->getByRmaId($rmaId);
            if ($easyReturn) {
                if ($easyReturn->getRegionId()) {
                    $regionName = $this->regionFactory->create()->load($easyReturn->getRegionId());
                    $easyReturn->setRegion($regionName->getName());
                }
                return $easyReturn->getPickUpAddress();
            }
        } catch (Exception $exception) {
            $this->_logger->critical($exception->getMessage(), ['exception' => $exception]);
        } catch (Throwable $throwable) {
            $this->_logger->critical($throwable->getMessage(), ['exception' => $throwable]);
        }

        return null;
    }
}
