<?php
declare(strict_types=1);
/**
 * Limesharp_Stockists extension
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the MIT License
 * that is bundled with this package in the file LICENSE
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/mit-license.php
 *
 * @category  Limesharp
 * @package   Limesharp_Stockists
 * @copyright 2016 Claudiu Creanga
 * @license   http://opensource.org/licenses/mit-license.php MIT License
 * @author    Claudiu Creanga
 */
namespace Limesharp\Stockists\Controller\Adminhtml\Stores;

use Magento\Framework\Registry;
use Limesharp\Stockists\Api\StockistRepositoryInterface;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\Stdlib\DateTime\Filter\Date;
use Magento\Backend\App\Action\Context;

use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Limesharp\Stockists\Controller\Adminhtml\Stores;

class Geocode extends Stores
{

    private $geocode;
    private $addressConfig;

    public function __construct(
        Registry $registry,
        StockistRepositoryInterface $stockistRepository,
        PageFactory $resultPageFactory,
        Date $dateFilter,
        Context $context,
        \Limesharp\Stockists\Model\Geocode $geocode,
        \Magento\Customer\Model\Address\Config $addressConfig

    ) {
        $this->coreRegistry      = $registry;
        $this->stockistRepository  = $stockistRepository;
        $this->resultPageFactory = $resultPageFactory;
        $this->dateFilter        = $dateFilter;
        $this->geocode        = $geocode;
        $this->addressConfig        = $addressConfig;
        parent::__construct($registry, $stockistRepository, $resultPageFactory, $dateFilter, $context);
    }

    /**
     * @return \Magento\Backend\Model\View\Result\Redirect
     */
    public function execute()
    {
        $resultRedirect = $this->resultRedirectFactory->create();
        $id = $this->getRequest()->getParam('stockist_id');
        if ($id) {
            try {
                $store = $this->stockistRepository->getById($id);
                $address = $this->getStoreFormattedAddress($store);
                if(empty($address)) {
                    $this->messageManager->addErrorMessage(__('Not found an address for store' . $id));
                    return $resultRedirect->setPath('stockists/stores/edit', ['stockist_id' => $id]);
                }

                $geocodeResponse = $this->geocode->geocode($address);
                $store->setLatitude($geocodeResponse['latitude']);
                $store->setLongitude($geocodeResponse['longitude']);
                $store->save();

                $this->messageManager->addSuccessMessage(__('The store has been geocoded.'));
                $resultRedirect->setPath('stockists/stores/edit', ['stockist_id' => $id]);
                return $resultRedirect;
            } catch (NoSuchEntityException $e) {
                $this->messageManager->addErrorMessage(__('The store no longer exists.'));
                return $resultRedirect->setPath('stockists/*/');
            } catch (LocalizedException $e) {
                $this->messageManager->addErrorMessage($e->getMessage());
                return $resultRedirect->setPath('stockists/stores/edit', ['stockist_id' => $id]);
            } catch (\Exception $e) {
                $this->messageManager->addErrorMessage(__('There was a problem geocoding the store (' . $id . '): ' . $e->getMessage()));
                return $resultRedirect->setPath('stockists/stores/edit', ['stockist_id' => $id]);
            }
        }
        $this->messageManager->addErrorMessage(__('We can\'t find a store to geocode.'));
        $resultRedirect->setPath('stockists/*/');
        return $resultRedirect;
    }

    /**
     * Format code 'text': Corso Cavour, 129 Bari, 70121 Italy T: 080 332 7281
     * Format code 'oneline': , Corso Cavour, 129, Bari, 70121, Italy
     * @param $store
     * @return null
     * TODO: Fare un cazzo di helper che sto modulo non ne ha e spostare tutti questi metodi li
     */
    public function getStoreFormattedAddress($store) {
        $formatType = $this->addressConfig->getFormatByCode('oneline');
        if (!$formatType || !$formatType->getRenderer()) {
            return null;
        }

        $addressArray = [
            'street' => $store->getAddress(),
            'city' => $store->getCity(),
            'region' => $store->getRegion(),
            'region_id' => $store->getRegion(),
            'postcode' => $store->getPostcode(),
            'country' => $store->getCountry(),
            'country_id' => $store->getCountry()
        ];
        //ltrim to remove customer firstname and lastname (customer address format mandatory need them)
        return ltrim($formatType->getRenderer()->renderArray($addressArray), ', ');
    }

}
