<?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\ViisonPickwareCommon\Classes\Util;
use Shopware\Plugins\ViisonPickwareERP\Components\RestApi\RequestLogging\AbstractRestApiRequestLogFilterSubscriber;

class RestApiRequestLogFilterSubscriber extends AbstractRestApiRequestLogFilterSubscriber
{
    /**
     * @inheritdoc
     */
    public function filterLoggedResponseJson(array $responseJson, \Enlight_Controller_Request_Request $request)
    {
        // Only filter responses of GETting or POSTing order documents
        $isDocumentGet = $request->getMethod() === 'GET' && $request->getParam('documents');
        $isDocumentPost = $request->getMethod() === 'POST' && $request->getParam('documents') === '';
        if ($request->getParam('controller') !== 'orders' || (!$isDocumentGet && !$isDocumentPost)) {
            return $responseJson;
        }

        if (isset($responseJson['data']['fileData'])) {
            $responseJson['data']['fileData'] = '<TRUNCATED>';
        }

        return $responseJson;
    }

    /**
     * @inheritdoc
     */
    public function shouldLogRequest(\Enlight_Controller_Request_RequestHttp $request)
    {
        // Whitelist all requests from Pickware apps
        $requestingAppName = Util::getRequestingAppName();
        $pickwarePluginBootstraps = $this->get('viison_pickware_common.device_licensing')->getAppSupportingPickwarePlugins();
        foreach ($pickwarePluginBootstraps as $plugin) {
            if (in_array($requestingAppName, $plugin->getNamesOfSupportedPickwareApps(), true)) {
                return true;
            }
        }

        return false;
    }

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