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

trait AcceptLanguageHeaderParsing
{
    /**
     * Parses the Accept-Language header of the active request.
     *
     * @param \Enlight_Controller_Request_RequestHttp $request
     * @return array an array of locales, sorted by priority
     */
    protected function parseAcceptLanguageHeader($request)
    {
        // This looks like "de-DE, en-US;q=0.9, en-GB;q=0.8"
        $headerValue = $request->getHeader('accept-language');

        $locales = array_map(
            function ($localeString) {
                $localeParts = explode(';', $localeString);
                // This looks like "en-US"
                $locale = $localeParts[0];
                $priority = 1;
                if (count($localeParts) > 1) {
                    // This looks like "q=0.9"
                    $q = $localeParts[1];
                    $qParts = explode('=', $q);
                    if (count($qParts) >= 2) {
                        $priority = floatval($qParts[1]);
                    }
                }
                // Convert IETF language tag to Unix-style locale
                $locale = str_replace('-', '_', trim($locale));

                return [
                    'locale' => trim($locale),
                    'priority' => $priority,
                ];
            },
            explode(',', $headerValue)
        );

        // Sort by priority (i.e. q-value)
        usort(
            $locales,
            function ($lhs, $rhs) {
                $difference = $lhs['priority'] - $rhs['priority'];
                if ($difference == 0) {
                    return 0;
                }

                return ($difference < 0) ? 1 : -1;
            }
        );

        // Return only locales
        return array_map(
            function ($locale) {
                return $locale['locale'];
            },
            $locales
        );
    }
}
