<?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\ViisonShippingCommon\Components\Logger;

/**
 * Class to log socket request/responses
 *
 * You need to implement abstract functions for filtering sensitive data.
 */
abstract class AbstractSocketLogger extends AbstractLogger
{
    /**
     * Logs the last request with level "debug"
     *
     * @param string $ip
     * @param string $port
     * @param string $request
     * @param string $response
     */
    public function logSuccessfulRequest($ip, $port, $request, $response)
    {
        $this->logger->debug(
            sprintf('Socket request to %s:%s executed.', $ip, $port),
            [
                'ip' => $ip,
                'port' => $port,
                'request' => $this->filterSensitiveDataIfNecessary($request),
                'response' => $this->filterSensitiveDataIfNecessary($response),
            ]
        );
    }

    /**
     * Logs a failed request with level "error"
     *
     * @param string $ip
     * @param string $port
     * @param string $request
     * @param int $errorCode
     * @param string $errorMessage
     */
    public function logFailedRequest($ip, $port, $request, $errorCode, $errorMessage)
    {
        $this->logger->error(
            sprintf('Socket request to %s:%s failed with error "%s".', $ip, $port, $errorMessage),
            [
                'ip' => $ip,
                'port' => $port,
                'errorCode' => $errorCode,
                'errorString' => $errorMessage,
                'request' => $this->filterSensitiveDataIfNecessary($request),
            ]
        );
    }

    /**
     * @param string $content
     * @return string
     */
    private function filterSensitiveDataIfNecessary($content)
    {
        if ($this->logSensitiveData) {
            return $content;
        }

        return $this->filterSensitiveData($content);
    }

    /**
     * Removes sensitive data from a request/response
     *
     * This should be login credentials or API keys
     *
     * @param string $content
     * @return string Filtered content
     */
    abstract public function filterSensitiveData($content);
}
