<?php
/**
 * Copyright © 2019 Wyomind. All rights reserved.
 * See LICENSE.txt for license details.
 */

namespace Wyomind\ElasticsearchLayeredNavigation\Controller;

use Magento\Framework\App\ActionFactory;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\ResponseInterface;
use Magento\Store\Model\StoreManager;
use Wyomind\ElasticsearchLayeredNavigation\Helper\Config;
use Wyomind\ElasticsearchLayeredNavigation\Model\ResourceModel\Category;

class Router implements \Magento\Framework\App\RouterInterface
{

    const MODULE_CATALOGSEARCH = "catalogsearch";
    const CONTROLLER_RESULT = "result";
    const ACTION_INDEX = "index";

    const MODULE_CATALOG = "catalog";
    const CONTROLLER_CATEGORY = "category";
    const ACTION_VIEW = "view";

    /**
     * @var ActionFactory
     */
    protected $actionFactory;

    /**
     * @var ResponseInterface
     */
    protected $_response;
    /**
     * @var Category
     */
    protected $categoryResourceModel;
    /**
     * @var Config
     */
    protected $configHelper;
    /**
     * @var StoreManager
     */
    protected $storeManager;

    /**
     * Router constructor.
     * @param ActionFactory $actionFactory
     * @param ResponseInterface $response
     * @param Category $categoryResourceModel
     * @param Config $configHelper
     * @param StoreManager $storeManager
     */
    public function __construct(
        ActionFactory $actionFactory,
        ResponseInterface $response,
        Category $categoryResourceModel,
        Config $configHelper,
        StoreManager $storeManager
    )
    {
        $this->actionFactory = $actionFactory;
        $this->_response = $response;
        $this->categoryResourceModel = $categoryResourceModel;
        $this->configHelper = $configHelper;
        $this->storeManager = $storeManager;
    }

    /**
     * @param RequestInterface $request
     * @return bool|\Magento\Framework\App\ActionInterface
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function match(RequestInterface $request)
    {
        $storeId = $this->storeManager->getStore()->getId();

        $identifier = str_replace($this->configHelper->getSEOCategoryUrlSuffix($storeId), '', trim($request->getPathInfo(), '/'));

        $params = explode("/", $identifier);

        if (count($params) >= 2) {
            $module = $params[0];
            $controller = $params[1];

            if (count($params) >= 3 && $module == self::MODULE_CATALOGSEARCH && $controller == self::CONTROLLER_RESULT) {

                $filters = [];
                $page = 1;
                $c = count($params);
                for ($i = 3; $i < $c; $i++) {
                    if (isset($params[$i + 1])) {
                        if ($params[$i] == "page") {
                            $page = $params[++$i];
                        } else {
                            $filters[$params[$i]] = $params[++$i];
                        }
                    }
                }

                $newParams = ["q" => $params[2], 'filters' => $filters, 'page' => $page];
                if ($request->getParam('dir')) {
                    $newParams['dir'] = $request->getParam('dir');
                }
                if ($request->getParam('order')) {
                    $newParams['order'] = $request->getParam('order');
                }
                $request->setParams($newParams);

                $request->setModuleName(self::MODULE_CATALOGSEARCH)
                    ->setControllerName(self::CONTROLLER_RESULT)
                    ->setActionName(self::ACTION_INDEX);

                return $this->actionFactory->create(
                    'Magento\Framework\App\Action\Forward',
                    ['request' => $request]
                );
            } else {


                $requestPath = trim($request->getPathInfo(), '/');
                $category = $this->categoryResourceModel->searchCategoryId($requestPath, $storeId);
                if (!$category) {
                    return false;
                }
                $category['request_path'] = str_replace($this->configHelper->getSEOCategoryUrlSuffix($storeId), '', $category['request_path']);

                $identifier = trim(str_replace([$category['request_path'], $this->configHelper->getSEOCategoryUrlSuffix($storeId)], '', $requestPath), '/');
                $params = explode("/", $identifier);

                $filters = [];
                $page = 1;
                $c = count($params);
                for ($i = 0; $i < $c; $i++) {
                    if (isset($params[$i + 1])) {
                        if ($params[$i] == "page") {
                            $page = $params[++$i];
                        } else {
                            $filters[$params[$i]] = $params[++$i];
                        }
                    }
                }

                $newParams = ['filters' => $filters, 'id' => $category['entity_id'], 'page' => $page];
                if ($request->getParam('dir')) {
                    $newParams['dir'] = $request->getParam('dir');
                }
                if ($request->getParam('order')) {
                    $newParams['order'] = $request->getParam('order');
                }
                $request->setParams($newParams);

                $request->setModuleName(self::MODULE_CATALOG)
                    ->setControllerName(self::CONTROLLER_CATEGORY)
                    ->setActionName(self::ACTION_VIEW);

                return $this->actionFactory->create(
                    'Magento\Framework\App\Action\Forward',
                    ['request' => $request]
                );
            }
        }


        return false;
    }

}