<?php

namespace FiloBlu\Storelocator\Controller;

use FiloBlu\Storelocator\Helper\Data;
use FiloBlu\Storelocator\Model\StoresFactory;
use Magento\Framework\App\Action\Forward;
use Magento\Framework\App\ActionFactory;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\RouterInterface;
use Magento\Framework\UrlInterface;

use function count;

/**
 *
 */
class Router implements RouterInterface
{
    /**
     * @var \Magento\Framework\App\ActionFactory
     */
    protected $actionFactory;

    /**
     * @var \FiloBlu\Storelocator\Helper\Data
     */
    protected $helper;

    /**
     * @var \FiloBlu\Storelocator\Model\StoresFactory
     */
    protected $storesFactory;

    /**
     * @param \Magento\Framework\App\ActionFactory $actionFactory
     * @param \FiloBlu\Storelocator\Helper\Data $helper
     * @param \FiloBlu\Storelocator\Model\StoresFactory $storeFactory
     */
    public function __construct(
        ActionFactory $actionFactory,
        Data $helper,
        StoresFactory $storeFactory
    ) {
        $this->actionFactory = $actionFactory;
        $this->helper = $helper;
        $this->storesFactory = $storeFactory;
    }

    /**
     * Validate and Match Cms Page and modify request
     *
     * @param \Magento\Framework\App\RequestInterface $request
     * @return \Magento\Framework\App\ActionInterface
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function match(RequestInterface $request)
    {
        $helper = $this->helper;

        if (!$helper->getConfig('filoblu_storelocator_section/general/enabled')) {
            return null;
        }

        $urlPrefix = $helper->getConfig('filoblu_storelocator_section/general/url_prefix');
        $urlSuffix = $helper->getConfig('filoblu_storelocator_section/general/url_suffix');
        $path = trim($request->getPathInfo(), '/');

        $storeModel = $this->storesFactory->create();
        $storeModel->load($path, 'url_key');

        if ($storeModel->getId()) {
            $request->setAlias(UrlInterface::REWRITE_REQUEST_PATH_ALIAS, $path . $urlSuffix);
            $request->setPathInfo('/storelocator/index/shop/id/' . $storeModel->getId());
            return $this->actionFactory->create(Forward::class);
        }

        if ($urlPrefix == '' || ($path != $urlPrefix . $urlSuffix)) {
            return null;
        }

        $array = explode('/', $path);

        if (count($array) !== 1) {
            return null;
        }

        $request->setAlias(UrlInterface::REWRITE_REQUEST_PATH_ALIAS, $path . $urlSuffix);
        $request->setPathInfo('/storelocator/index/index');

        return $this->actionFactory->create(Forward::class);
    }
}
