<?php

/**
 * Created by PhpStorm.
 * User: jderosa
 * Date: 29/04/20
 * Time: 11.15
 */

namespace FiloBlu\Rma\Block\Email;

use Exception;
use FiloBlu\Rma\Api\EasyReturnRepositoryInterface;
use FiloBlu\Rma\Helper\EasyReturnHelper;
use Magento\Directory\Model\RegionFactory;
use Magento\Eav\Model\Config;
use Magento\Eav\Model\Form\Factory;
use Magento\Framework\Data\Collection\ModelFactory;
use Magento\Framework\View\Element\Template\Context;
use Magento\Rma\Helper\Eav;
use Magento\Sales\Api\Data\OrderAddressInterface;
use Throwable;

/**
 *
 */
class PickupAddress extends \Magento\Rma\Block\Email\Items
{
    /**
     * @var EasyReturnHelper
     */
    protected $easyReturnHelper;
    /**
     * @var EasyReturnRepositoryInterface
     */
    private $easyReturnRepository;

    /**
     * @var RegionFactory
     */
    private $regionFactory;

    /**
     * PickupAddress constructor.
     * @param Context $context
     * @param ModelFactory $modelFactory
     * @param Factory $formFactory
     * @param Config $eavConfig
     * @param Eav $rmaEav
     * @param EasyReturnRepositoryInterface $easyReturnRepository
     * @param RegionFactory $regionFactory
     * @param \FiloBlu\Rma\Helper\EasyReturnHelper $easyReturnHelper
     * @param array $data
     */
    public function __construct(
        Context $context,
        ModelFactory $modelFactory,
        Factory $formFactory,
        Config $eavConfig,
        Eav $rmaEav,
        EasyReturnRepositoryInterface $easyReturnRepository,
        RegionFactory $regionFactory,
        EasyReturnHelper $easyReturnHelper,
        array $data = []
    ) {
        parent::__construct($context, $modelFactory, $formFactory, $eavConfig, $rmaEav, $data);
        $this->easyReturnRepository = $easyReturnRepository;
        $this->regionFactory = $regionFactory;
        $this->easyReturnHelper = $easyReturnHelper;
    }

    /**
     * @param $rmaId
     * @return bool
     */
    public function isEasyReturn($rmaId)
    {
        return $this->easyReturnHelper->isEasyReturn($rmaId);
    }

    /**
     * @param $rmaId
     * @return OrderAddressInterface|string
     */
    public function getPickupAddress($rmaId)
    {
        try {
            $pickupAddress = $this->easyReturnRepository->getByRmaId($rmaId);
            if ($pickupAddress->getRegionId()) {
                $regionName = $this->regionFactory->create()->load($pickupAddress->getRegionId());
                $pickupAddress->setRegion($regionName->getName());
            }
            return $pickupAddress->getPickUpAddress();
        } catch (Exception $e) {
            $this->_logger->critical($e->getMessage(), ['exception' => $e]);
            return '';
        } catch (Throwable $t) {
            $this->_logger->critical($t->getMessage(), ['exception' => $t]);
            return '';
        }
    }
}
