<?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\ViisonDHL\Classes;

/**
 * Class DHLApiMessageToSnippetTranslator
 */
class DHLApiMessageToSnippetTranslator
{
    public static $apiMessageToSnippetMapping = [
        /**
         * @errorCode 0
         * Original message: (using trimmed message for matching, because of the EKP number)
         * ‌Invalid XML: cvc-length-valid: Value 'EKP_NUMBER' with length = '12' is not facet-valid with respect to
         * length '14' for type '#AnonType_billingNumberAbstractShipmentType'.
         */
        'INVALID_BILLING_NUMBER' => [
            'message' => '#AnonType_billingNumberAbstractShipmentType',
            'snippet' => 'invalidBillingNumber',
        ],
        /** @errorCode 500 */
        'TOO_MANY_CONNECTIONS' => [
            'message' => 'too many connections',
            'snippet' => 'loginFailedInDHLPortal',
        ],
        /** @errorCode 1001 */
        'LOGIN_FAILED' => [
            'message' => 'Der Nutzer des Webservice konnte nicht authentifiziert werden.',
            'snippet' => 'loginFailedInDHLPortal',
        ],
        /**
         * @errorCode 1101
         * Whole Message:
         * Die Packstationsnummer ist uns aktuell nicht bekannt. Bitte überprüfen Sie die Nummer und die
         * Postleitzahl. Es kann in Einzelfällen sein, dass eine neue Packstation noch nicht bekannt ist. Sie
         * können trotzdem eine leitcodierte Sendung erzeugen.',
         */
        'INVALID_PACKING_STATION_NUMBER' => [
            'message' => 'Es kann in Einzelfällen sein, dass eine neue Packstation noch nicht bekannt ist. Sie können trotzdem eine leitcodierte Sendung erzeugen',
            'snippet' => 'invalidPackingStationNumber',
        ],
        /**
         * @errorCode 1101
         */
        'REQUIRES_EXPORT_DECLARATION' => [
            'message' => 'Waren, die eine Ausfuhranmeldung benötigen, müssen mit DHL Paket International versendet werden.',
            'snippet' => 'requiresExportDeclaration',
        ],
    ];

    /**
     * Translated error codes for snippets
     * ( There is a use case in DHL Adapter where we have custom error codes that trigger specific conditions )
     */
    public static $snippetToCustomErrorCodeMapping = [
        'INVALID_PACKING_STATION_NUMBER' => [
            'snippet' => 'invalidPackingStationNumber',
            'errorCode' => NonCodableAddressDHLException::ERROR_CODE,
        ],
    ];

    /**
     * @param string $apiMessage
     * @return mixed|string
     */
    public static function getSnippetNameForMessage($apiMessage)
    {
        $apiMessage = self::transformMessageToLowerCaseWithSingleWhiteSpace($apiMessage);
        foreach (self::$apiMessageToSnippetMapping as $mapping) {
            if (self::isApiMessage($apiMessage, mb_strtolower($mapping['message'], 'UTF-8'))) {
                return $mapping['snippet'];
            }
        }

        return null;
    }

    /**
     * @param string $snippet
     * @return string|null
     */
    public static function getTranslatedErrorCodeForSnippetIfExist($snippet)
    {
        foreach (self::$snippetToCustomErrorCodeMapping as $mapping) {
            if (mb_strpos($mapping['snippet'], $snippet) !== false) {
                return $mapping['errorCode'];
            }
        }

        return null;
    }

    /**
     * @param string $apiMessage
     * @param string $message
     * @return bool
     */
    protected static function isApiMessage($apiMessage, $message)
    {
        return mb_strpos($apiMessage, $message) !== false;
    }

    /**
     * @param string $message
     * @return string
     */
    protected static function transformMessageToLowerCaseWithSingleWhiteSpace($message)
    {
        // Transform api message to lower case with single white space
        $message = preg_replace('!\\s+!', ' ', $message);
        $message = mb_strtolower($message, 'UTF-8');

        return $message;
    }
}
