<?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;

use Shopware\Components\DependencyInjection\Container;
use Shopware\Components\Model\ModelManager;
use Shopware\Models\Shop\Locale;
use Shopware\Plugins\ViisonCommon\Classes\Util\Localization as LocalizationUtil;
use Shopware\Plugins\ViisonCommon\Components\AcceptLanguageHeaderParsing;
use Shopware\Plugins\ViisonCommon\Components\Localization\SnippetManagerService;

/**
 * A snippet manager that looks up snippets based on the contents of the Accept-Language header.
 */
class LocalizedApiSnippetManager extends SnippetManagerService
{
    use AcceptLanguageHeaderParsing;

    public function __construct(Container $container, \Enlight_Controller_Request_RequestHttp $request)
    {
        parent::__construct($container);

        $headerLocales = $this->parseAcceptLanguageHeader($request);

        // Try to convert any parsed locales that only contain a language identifier (e.g. 'en') to a full locale
        // consisting of languge and territory (e.g. 'en_GB')
        $locales = array_values(array_filter(array_map(
            function ($headerLocale) {
                return (mb_strpos($headerLocale, '_') === false) ? LocalizationUtil::getPrimaryLocaleForLanguage($headerLocale) : $headerLocale;
            },
            $headerLocales
        )));

        /** @var ModelManager $modelManager */
        $modelManager = $container->get('models');
        /** @var Locale[] $locales */
        $locales = array_values(
            array_filter(
                array_map(
                    function ($localeIdentifier) use ($modelManager) {
                        return $modelManager->getRepository('Shopware\\Models\\Shop\\Locale')->findOneBy(
                            [
                                'locale' => $localeIdentifier,
                            ]
                        );
                    },
                    $locales
                )
            )
        );
        if (empty($locales)) {
            $locales[] = $modelManager->getRepository('Shopware\\Models\\Shop\\Shop')->getDefault()->getLocale();
        }
        $this->extends = array_map(
            function (Locale $locale) {
                return [
                    1,
                    $locale->getId(),
                ];
            },
            $locales
        );
        $this->locale = $locales[0];
    }
}
