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

use Shopware\Components\DependencyInjection\Container;
use Shopware_Components_Snippet_Manager;

class SnippetManagerService extends Shopware_Components_Snippet_Manager
{
    /**
     * @inheritdoc
     */
    public function __construct(Container $container)
    {
        $entityManager = $container->get('models');
        $snippetParam = $container->getParameter('shopware.snippet');

        // The 'shopware.template.templateDir' parameter was added in 5.5.9 and is used in the
        // Shopware_Components_Snippet_Manager to find snippet (.ini) files. This parameter is relevant if the Shopware
        // config is set to load snippets from ini files instead of the database.
        if ($container->hasParameter('shopware.template.templateDir')) {
            $templateDir = sprintf('%s/Frontend', $container->getParameter('shopware.template.templateDir'));
        } else {
            $templateDir = null;
        }

        // With Shopware 5.2.0 Shopware_Components_Snippet_Manager needs the plugin directories as constructor argument.
        // The parameter shopware.plugin_directories was also introduced in Shopware 5.2.0 so we can use it to determine
        // if the Shopware version is higher than 5.2.0.
        if ($container->hasParameter('shopware.plugin_directories')) {
            parent::__construct(
                $entityManager,
                $container->getParameter('shopware.plugin_directories'),
                $snippetParam,
                $templateDir
            );
        } else {
            parent::__construct($entityManager, $snippetParam);
        }

        $this->adapter = new SnippetDbAdapter($container->get('dbal_connection'), $entityManager);

        // Copy the defaul snippet manager's shop and locale, if available, to provide the correct context for the
        // language fallback chain. We must do this here manually, since the default snippet manager is modified by
        // Shopware's auth plugin before dispatching the request.
        $defaultSnippetManager = $container->get('snippets');
        if ($defaultSnippetManager->shop) {
            $this->setShop($defaultSnippetManager->shop);
        }
        if ($defaultSnippetManager->locale) {
            $this->setLocale($defaultSnippetManager->locale);
        }
    }
}
