<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

namespace Shopware\Plugins\ViisonPickwareCommon\Subscribers;

use Shopware\Plugins\ViisonPickwareERP\Components\RestApi\Routing\AbstractRestApiRouterSubscriber;
use Shopware\Plugins\ViisonPickwareERP\Components\RestApi\Routing\RestApiRouterService;

class RestApiRouterSubscriber extends AbstractRestApiRouterSubscriber
{
    /**
     * @var bool
     */
    private $requestHasBeenMadeCompatible = false;

    /**
     * @inheritDoc
     */
    public static function getSubscribedEvents()
    {
        // Ensure that the routing of PickwareCommon is executed before every other routing because the routing of
        // PickwareCommon does the API request compatibility layering. This acts as routing but needs to be done
        // before every other routing.
        $subscribedEvent = parent::getSubscribedEvents();
        $apiControllerRoutingEvent = $subscribedEvent[RestApiRouterService::EVENT_REST_API_CONTROLLER_ROUTING];
        if (is_array($apiControllerRoutingEvent)) {
            $apiControllerRoutingEvent = [
                $apiControllerRoutingEvent[0],
                $apiControllerRoutingEvent[1] - 1000,
            ];
        } else {
            $apiControllerRoutingEvent = [
                $apiControllerRoutingEvent,
                -1000,
            ];
        }
        $subscribedEvent[RestApiRouterService::EVENT_REST_API_CONTROLLER_ROUTING] = $apiControllerRoutingEvent;

        return $subscribedEvent;
    }

    /**
     * @inheritdoc
     */
    public function applyCustomRouting(\Enlight_Controller_Request_Request $request)
    {
        // Check whether the compatibility layer is required
        $requestCompatibilityManager = $this->get('viison_pickware_common.api_request_compatibility_manager');
        if (!$requestCompatibilityManager->isRequestCompatible($request) && !$this->requestHasBeenMadeCompatible) {
            // The controller ViisonPickwareCommonApiRequestCompatibilityContainer does routing by itself after
            // API request compatibility layering. Use this flag to avoid infinity routing to the compatibility
            // container
            $this->requestHasBeenMadeCompatible = true;

            return 'ViisonPickwareCommonApiRequestCompatibilityContainer';
        }

        $controllerName = $request->getParam('controller');
        $method = $request->getMethod();

        $isDocumentGet = $method === 'GET' && $request->getParam('documents');
        $isDocumentPost = $method === 'POST' && ($request->getParam('documents') === '');
        $isDocumentSend = $method === 'POST' && ($request->getParam('send') === '');
        if ($controllerName === 'orders' && ($isDocumentGet || $isDocumentPost || $isDocumentSend)) {
            return 'ViisonPickwareCommonOrders';
        }

        if ($controllerName === 'documents'
            && ($method === 'GET' || ($method === 'POST' && $request->getParam('send') === ''))
        ) {
            return 'ViisonPickwareCommonDocuments';
        }

        if ($controllerName === 'pickware') {
            // Use the request's 'id' parameter as the name of the targeted action, because requests
            // to the 'pickware' resource don't follow the default API format, but rather the format
            // '/api/pickware/<ACTION_NAME>'
            $request->setActionName($request->getParam('id'));

            return 'ViisonPickwareCommonPickware';
        }

        if ($controllerName === 'variants'
            && (
                ($method === 'GET' && ($request->getParam('action') === null || $request->getParam('action') === 'index' || $request->getParam('binLocationMappings') !== null))
                || ($method === 'POST' && $request->getParam('binLocationMappings') === '')
                || ($method === 'PUT' && $request->getParam('binLocationMappings') !== null)
                || ($method === 'DELETE' && $request->getParam('binLocationMappings') !== null && $request->getParam('stockReservations') !== null)
            )
        ) {
            return 'ViisonPickwareCommonVariants';
        }

        return null;
    }

    /**
     * {@inheritdoc}
     *
     * Overrides the default implementation to return the path to this library's root path.
     */
    public function getPluginPath()
    {
        return __DIR__ . '/../';
    }
}
